[英]How to access a setter through an instance of object.create
在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?
這是用小提琴鏈接設置的代碼
只需像這樣設置o.bar
即可調用“設置”功能:
o.bar = 3
Setting `o.bar` to 3
3
編輯:
正如@CyberneticTwerkGuruOrc在評論中提到的那樣,在這種情況下,設置程序不會設置任何內容。 為此,您必須使用輸入value
並實際設置一些(其他)值,例如: this.foo = value
如果要處理@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.