我需要在JavaScript中为嵌套对象创建getter和setter。
目前我在下面的代码中使用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);
答案 0 :(得分:1)
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();