将原型上的__defineGetter__和__defineSetter__替换为 defineProperty
replace __defineGetter__ and __defineSetter__ on the prototype with defineProperty
我目前使用以下语法来定义一个带有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);
如何使用未弃用的 definecProperty 命令或类似命令实现相同的目标?
我尝试了这样的事情:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(this),
set: function(value) {
this._propertyOne = value;
}.bind(this)
});
但它不起作用。
在你运行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)
部分,它应该可以正常工作。
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 我如何找到一个句子中的所有空格并替换忽略它们
- 如何用更合适的内容替换document.write
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 用空格替换下划线PHP
- str.split(someString).join(someOtherString)是否等效于替换
- 使用javascript的图像替换循环
- window.location替换并传递URL历史记录条目中的变量
- 替换标记中的属性
- 指令的模板必须只有一个根元素:With restrict E&替换true
- AngularJs对ng消息的自定义替换
- 用超链接替换URLS
- 用cdata标记替换脚本标记
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 在javascript中,I'我很难弄清楚如何让regex只替换捕获而不替换匹配
- 替换url中变量的值
- 我希望在不替换现有变量的情况下恢复localStorage中的变量
- Wordpress:替换源(域名)链接
- javascript替换换行符和特殊字符