對象的 set get 是es5的中對象的特性,使用示例:
在初始化對象的時候這樣使用
var obj={
a: 1,
b: 2,
set c(x){console.log('c被賦值:',x);c=x;},
get c(){console.log('c被取出: ',c);return c}
};
obj.c=3 //c被賦值: 3
obj.c //c被取出: 3
對象初始化之后可以這樣添加屬性
var obj={
a: 1,
b: 2
};
obj.__defineGetter__('c', function(){return c});
obj.__defineSetter__('c', function(x){c = x});
或者使用
Object.defineProperty(obj, c, {
set:function(x){
console.log('c被賦值:',x);
c=x
},
get:function(){
console.log('c被取出:',c)
return c
}
})
obj.c=3 //c被賦值: 3
obj.c //c被取出: 3
