[英]Concise definition of Getter and Setter for nesting properties of an object in ES5 or ES6
我需要創建getter和setter以便在JavaScript中嵌套對象。 目前,我在下面的代碼中使用Object.defineProperty()
。
定位到ES5或ES6。
我想要
var base = { _name: 'default', _properties: { _top: 0 }, constructor: function () { } }; Object.defineProperty(base, 'name', { get: function () { return this._name; }, set: function (value) { this._name = value; } }); Object.defineProperty(base, 'properties', { get: function () { return this._properties; }, set: function (value) { this._properties = value; } }); // nesting properties Object.defineProperty(base.properties, 'top', { get: function () { return this._properties._top; }.bind(base), set: function (value) { this._properties._top = value; console.log('WORKS!'); }.bind(base) }); console.log(base.name); base.name = 'Foo'; console.log(base.name); console.log(base.properties.top); base.properties.top = 1000; console.log(base.properties.top);
這是主意嗎? 通過jsbin上的babel測試並運行es6。
var base = {
_name: 'default',
get name() {
return this._name;
},
set name(n) {
return this._name = n;
},
_properties: {
_top: 0,
get top() {
return this._top;
},
set top(t) {
return this._top = t;
},
},
get properties() {
return this._properties;
},
};
或基於類的版本:
class Base {
constructor() {
this._name = 'default';
this._properties = {
_top: 0,
get top() { return this._top; },
set top(val) { return this._top = val; }
};
}
get name() {
return this._name;
}
set name(n) {
return this._name = n;
}
get properties() {
return this._properties;
}
}
var b = new Base();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.