两种定义形式。
第一种:
var o = {
age:'123',
name:'gmm',
get age(){
return "2";
},
set age(x){
return this.name ="Eliza";
}
};
o.age = 1;
console.log(o.name); //Eliza
console.log(o.age); //2
第二种:
var obj = {
a: 12
};
Object.defineProperty(obj, "x", {
get: function() {
return this.a + 1
},
enumerable: true,
configurable: true,
set: function(y) {
console.log(y);
},
});
console.log(obj.x); //3
obj.x = 3; //执行set(3)
console.log(obj.x); //3
console.log(delete obj.x); //true
for (key in obj) {
console.log(obj[key]); //12
}
注意不能同时设置value和getter/setter,因为这两种都是这是指的~