Use Object.defineProperty to define property - Node.js Object

Node.js examples for Object:Property

Description

Use Object.defineProperty to define property

Demo Code

var account = {/*  w  w w  . j  a  v a 2 s.co  m*/
    cash: 12000,
    _name: 'Default',
    withdraw: function(amount) {
        this.cash -= amount;
        console.log('Withdrew ' + amount + ', new cash reserve is: ' + this.cash);
    }
};

Object.defineProperty(account, 'deposit', {
    value: function(amount) {
        this.cash += amount;
    }
});

account.deposit(3000);
account.withdraw(1000);


// from default, read-only. Need to add writable to true

Object.defineProperty(account, 'name', {
    value: 'ID000-1',
    writable: true
});

console.log(account.name);
account.name = 'ID000-3';
console.log(account.name);

Object.defineProperty(account, 'name', {
    get: function() {
        return this._name;
    },
    set: function(name) {
        if (name === 'Isak') {
            this._name = name;
        }
    }
});

account.name = 'ID000-3';
console.log(account.name);


var person = {
    name: 'Isak',
    age: 34,
    greet: function() {
        console.log('Hello');
    }
};

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

// delete a property from an object
//delete person.name;

// check if property exist in person object.
console.log('name' in person);

// loop through an object using the for ... of loop
for (var field in person) {
    console.log(person[field]);
}

Related Tutorials