我目前使用以下语法来定义具有getter和setter的类。
SomeObject = function() {
this._propertyOne = 'test';
}
SomeObject.prototype.__defineGetter__('propertyOne', function() {
return this._propertyOne;
});
SomeObject.prototype.__defineSetter__('propertyOne', function(value) {
this._propertyOne = value;
});
然后我可以像这样访问该属性:
var o = new SomeObject();
o.propertyOne = 'test2';
console.log(o.propertyOne);
如何使用非弃用的defineProperty命令或类似的东西实现相同的目标?
我试过这样的事情:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(this),
set: function(value) {
this._propertyOne = value;
}.bind(this)
});
但它不起作用。
答案 0 :(得分:5)
当您运行Object.defineProperty
时,this
值不是您想要的值,而是window
(或您运行该代码段的对象)。所以这就是实际发生的事情:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(window),
set: function(value) {
this._propertyOne = value;
}.bind(window)
});
删除.bind(this)
部分,它应该可以正常工作。