我目前使用以下语法来定义具有getter和setter的类.
SomeObject = function() {
this._propertyOne = 'test';
}
SomeObject.prototype.__defineGetter__('propertyOne', function() {
return this._propertyOne;
});
SomeObject.prototype.__defineSetter__('propertyOne', function(value) {
this._propertyOne = value;
});
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样访问该属性:
var o = new SomeObject();
o.propertyOne = 'test2';
console.log(o.propertyOne);
Run Code Online (Sandbox Code Playgroud)
如何使用非弃用的defineProperty命令或类似的东西实现相同的功能?
我试过这样的事情:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(this),
set: function(value) {
this._propertyOne = value;
}.bind(this)
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
在您运行的那一刻Object.defineProperty,该this值不是您想要的值,而是window(或者您运行该代码段的对象).所以这就是实际发生的事情:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(window),
set: function(value) {
this._propertyOne = value;
}.bind(window)
});
Run Code Online (Sandbox Code Playgroud)
删除.bind(this)部件,它应该工作正常.
| 归档时间: |
|
| 查看次数: |
1851 次 |
| 最近记录: |