Properties
Javascript allows you to define special getter and setter functions that you can access as a field via. operation. When you read the value, the getter will be called if it exists. When you write a value, the setter will be used if it exists.
The get keyword specifies a getter.
The set keyword specifies a setter.
var obj1 = {
items: [],
get first(){
// return this.items[0] if you want automatically
// to add first element with undefined value
return this.items.length==0? undefined : this.items[0];
},
set first(val){
// this.items.push(val) if you want to add new first
this.items[0]=val;
}
}
console.log("read first: ", obj1.first); // undefined
obj1.first = 45;
console.log("read first: ", obj1.first); // 45
obj1.first = 90;
console.log("read first: ", obj1.first); // 90
class PropDemo{
items = [];
get first(){
return this.items.length==0? undefined : this.items[0];
}
set first(val){
this.items[0]=val;
}
}
var obj2 = new PropDemo();
console.log("read first: ", obj2.first); // undefined
obj2.first = 45;
console.log("read first: ", obj2.first); // 45
obj2.first = 90;
console.log("read first: ", obj2.first); // 90
add property dynamically
You can add property via Object.defineProperty() method. Unlike get/set, in this case property will be added to the object instance, not to the prototype.
const o = {a: 0};
Object.defineProperty(o, 'b',
{ get: function() { return this.a + 1; } });
console.log(o.b) // a + 1, i.e. 1
remove property
You can remove property using operator delete. if no more references to the same property are held, it is eventually released automatically.
If the property was defined using Object.defineProperty () , it must be configurable. Otherwise, the delete operator will be ignored.
const Employee = {
firstname: 'John',
lastname: 'Doe'
};
console.log(Employee.firstname); // John
delete Employee.firstname;
console.log(Employee.firstname); // undefined
const o = {a: 0};
Object.defineProperty(o, 'b',
{ get: function() { return this.a + 1; } });
console.log(o.b); // a + 1, i.e. 1
// the property will not be removed
// because it is not configurable
delete o.b;
console.log("o.b after delete", o.b); // a + 1, i.e. 1
const o2 = {a: 0};
Object.defineProperty(o2, 'b',
{ configurable: true, // false by default
get: function() { return this.a + 1; }
});
delete o2.b;
console.log("o2.b after delete", o2.b); // undefined
computed property name
ECMAScript 2015 supports a computed property name.
const expr = 'foo';
const obj = {
baz: 'bar',
set [expr](v) { this.baz = v; }
};
console.log(obj.baz); // "bar"
obj.foo = 'baz';
console.log(obj.baz); // "baz"