The below code demonstrates usage of defineProperty in JS:
var BankAccount = {
cash: 12000,
_name:"Default",
withdraw: function(amount){
this.cash -= amount;
console.log('Withdrew '+ amount + ', new cash reserve is: '+ this.cash);
}
};
//BankAccount.withdraw(1000);
Object.defineProperty(BankAccount, 'deposit',{
value: function(amount) {
this.cash += amount;
}
});
BankAccount.deposit(3000);
BankAccount.withdraw(1000);
/*
Object.defineProperty(BankAccount, 'name',{
value : 'ID000-1',
writable: true
// by default, properties created using defineProperty = readOnly
});
console.log(BankAccount.name);
*/
BankAccount.name = 'Sandra';
console.log(BankAccount.name);
Object.defineProperty(BankAccount,'name',{
get: function() {
return this._name;
} ,
set: function(name) {
this._name=name;
}
})
BankAccount.name = 'Cassandra';
console.log(BankAccount.name);
Practice at:
http://jsbin.com
var BankAccount = {
cash: 12000,
_name:"Default",
withdraw: function(amount){
this.cash -= amount;
console.log('Withdrew '+ amount + ', new cash reserve is: '+ this.cash);
}
};
//BankAccount.withdraw(1000);
Object.defineProperty(BankAccount, 'deposit',{
value: function(amount) {
this.cash += amount;
}
});
BankAccount.deposit(3000);
BankAccount.withdraw(1000);
/*
Object.defineProperty(BankAccount, 'name',{
value : 'ID000-1',
writable: true
// by default, properties created using defineProperty = readOnly
});
console.log(BankAccount.name);
*/
BankAccount.name = 'Sandra';
console.log(BankAccount.name);
Object.defineProperty(BankAccount,'name',{
get: function() {
return this._name;
} ,
set: function(name) {
this._name=name;
}
})
BankAccount.name = 'Cassandra';
console.log(BankAccount.name);
Practice at:
http://jsbin.com
No comments:
Post a Comment