Javascript 定义属性
Javascript defineProperty
使用时:
Object.defineProperty(obj,prop,desc){
get: function(){...
set: function(){...
}
无论指定什么 属性,getter/setter 是适用于 obj[prop]
还是作用于 obj
?
我问是因为我正在尝试基于嵌套对象设置一些数据绑定,例如:
obj[propA] = {propB:'seomthing',propC:'somethingElse'}
当我做这样的事情时:
var obj = {value:{propA:'testA',propB:'testB'}};
Object.defineProperty(obj.value,'propA',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propA: ',newValue);}
});
console.log(obj.value.propA);
obj.value.propA = 'testA';
Object.defineProperty(obj.value,'propB',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propB: ',newValue);}
});
console.log(obj.value.propB);
obj.value.propB = 'testB';
console.log('propA: ',obj.value.propA,' --propB: ',obj.value.propB);
getter 将值分配给对象内 defineProperty
设置的所有属性。
如果这是正确的功能,有没有办法让 getter/setter 仅在 属性 上工作,这样在上面的 fiddle 中,propA 会产生 testA 和propB 会产生 testB?
getter和setter只适用于命名的属性,但每个里面的this
指的是属性是的对象(你不必为每个 属性).
都有一个支持变量
在您的示例中,您始终在读取和修改 obj.value.value
。您可以通过将每个变量包装在一个 IIFE 中来为每个变量创建一个不同的变量,例如:
(function () {
var value;
Object.defineProperty(obj.value, 'propA', {
get: function () { return value; },
set: function (newValue) { value = newValue; },
});
})();
使用时:
Object.defineProperty(obj,prop,desc){
get: function(){...
set: function(){...
}
无论指定什么 属性,getter/setter 是适用于 obj[prop]
还是作用于 obj
?
我问是因为我正在尝试基于嵌套对象设置一些数据绑定,例如:
obj[propA] = {propB:'seomthing',propC:'somethingElse'}
当我做这样的事情时:
var obj = {value:{propA:'testA',propB:'testB'}};
Object.defineProperty(obj.value,'propA',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propA: ',newValue);}
});
console.log(obj.value.propA);
obj.value.propA = 'testA';
Object.defineProperty(obj.value,'propB',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propB: ',newValue);}
});
console.log(obj.value.propB);
obj.value.propB = 'testB';
console.log('propA: ',obj.value.propA,' --propB: ',obj.value.propB);
getter 将值分配给对象内 defineProperty
设置的所有属性。
如果这是正确的功能,有没有办法让 getter/setter 仅在 属性 上工作,这样在上面的 fiddle 中,propA 会产生 testA 和propB 会产生 testB?
getter和setter只适用于命名的属性,但每个里面的this
指的是属性是的对象(你不必为每个 属性).
在您的示例中,您始终在读取和修改 obj.value.value
。您可以通过将每个变量包装在一个 IIFE 中来为每个变量创建一个不同的变量,例如:
(function () {
var value;
Object.defineProperty(obj.value, 'propA', {
get: function () { return value; },
set: function (newValue) { value = newValue; },
});
})();