Javascript 如何通过object.create实例访问setter
在mozilla网站上,他们说:Javascript 如何通过object.create实例访问setter,javascript,Javascript,在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: { w
// 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
下面是用小提琴设置的代码只需像这样设置
o.bar
即可调用“set”功能:
o.bar = 3
Setting `o.bar` to 3
3
编辑:
正如@controlnetictwerkguroorc在评论中提到的,setter在这种情况下没有设置任何内容。为此,您必须使用输入
值
并实际设置一些(其他)值,例如:this.foo=value
只需像这样设置o.bar
即可调用“set”功能:
o.bar = 3
Setting `o.bar` to 3
3
编辑:
正如@controlnetictwerkguroorc在评论中提到的,setter在这种情况下没有设置任何内容。为此,您必须使用输入
值
并实际设置一些(其他)值,例如:this.foo=value
如果您想处理由引起的问题,可以这样编写,将实际值存储在内部闭包变量中:
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
如果要处理由引发的问题,可以这样编写,将实际值存储在内部闭包变量中:
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
比你想象的要容易,我猜:
o.bar=20但是,请注意,log语句中对变量名的引用可能不是很好:var p=o;p、 巴=20代码>日志:“将o.bar
设置为20”,这可能有点令人惊讶。o.bar=15
可以工作并在控制台中打印。但是,o.bar
仍将返回10
;你认为你可以怎样称呼o.bar?这是一个数字,不是一个函数。我猜比你想象的要简单:o.bar=20但是,请注意,log语句中对变量名的引用可能不是很好:var p=o;p、 巴=20代码>日志:“将o.bar
设置为20”,这可能有点令人惊讶。o.bar=15
可以工作并在控制台中打印。但是,o.bar
仍将返回10
;你认为你可以怎样称呼o.bar?这是一个数字,不是一个函数。我建议您提及OP的setter
方法实际上并没有设置任何内容。啊哈!我期待着o.bar(arg);这太奇怪了!我建议您提一下OP的setter
方法实际上并没有设置任何东西。啊哈!我期待着o.bar(arg);这太奇怪了!