在Mozilla网站上,他们说:
// Example where we create an object with a couple of sample properties.
// (Note that the second parameter maps keys to *property descriptors*.)
o = Object.create(Object.prototype, {
// foo is a regular 'value property'
foo: { writable: true, configurable: true, value: 'hello' },
// bar is a getter-and-setter (accessor) property
bar: {
configurable: false,
get: function() { return 10; },
set: function(value) { console.log('Setting `o.bar` to', value); }
/* with ES5 Accessors our code can look like this
get function() { return 10; },
set function(value) { console.log('setting `o.bar` to', value); } */
}
});
但是当我运行这段代码时,我可以调用o.bar但是我可以调用set方法吗?
o.bar调用get,但是如何调用set?
以下是使用小提琴LINK
设置的代码答案 0 :(得分:3)
只需像这样设置o.bar
即可调用'set'函数:
o.bar = 3
Setting `o.bar` to 3
3
修改强>
正如@CyberneticTwerkGuruOrc在评论中提到的那样,在这种情况下,setter不会设置任何内容。为此,您必须使用输入value
并实际设置一些(其他)值,例如:this.foo = value
答案 1 :(得分:1)
如果你想处理@CyberneticTwerkGuruOrc引发的问题,可以这样写,将实际值存储在内部闭包变量中:
o = Object.create(Object.prototype, {
foo: { writable: true, configurable: true, value: 'hello' },
bar: (function() {
var internalValue = 10;
return {
configurable: false,
get: function() { return internalValue; },
set: function(value) {
console.log('Setting `bar` to', value);
internalValue = value;
}
};
}())
});
o.bar; //=> 10
o.bar = 12; // logs 'Setting `bar` to 12'.
o.bar; //> 12