在 JavaScript 中修饰实例方法时出现问题
Problems decorating an instance method in JavaScript
我在 ES6 中装饰实例方法时遇到了一个难题。我在装饰该方法时没有问题,但似乎它被类实例的单一状态所困扰。这是我具体处理的内容:
class Test {
init() {
this.foo = 'bar';
}
@decorator
decoratedMethod() {
console.log(this.foo); // undefined
}
}
let test = new Test();
test.init();
test.decoratedMethod();
function decorator(target, name, descriptor) {
let fn = target[ name ].bind(target, 'a', 'b');
return fn;
}
我意识到上面的代码正在做它应该做的事情,但是如果我想访问添加到范围内的foo
和其他属性,我该如何装饰decoratedMethod
并仍然绑定新的函数属性?
方法修饰器在类声明时运行一次,而不是在类实例化时运行一次。这意味着示例中的target
是Test.prototype
,而不是实例。所以你的例子本质上是:
class Test {
init() {
this.foo = 'bar';
}
decoratedMethod() {
console.log(this.foo); // undefined
}
}
Test.prototype.decoratedMethod =
Test.prototype.decoratedMethod.bind(Test.prototype, 'a', 'b');
这应该清楚地说明为什么你的代码失败了。要绑定的对象没有foo
属性,只有实例具有。
处理装饰器,事情会变得更加复杂,您需要在创建实例后进行绑定。一种方法是
function decorator(target, name, descriptor){
const {value} = descriptor;
delete descriptor.value;
delete descriptor.writable;
descriptor.get = function(){
// Create an instance of the bound function for the instance.
// And set an instance property to override the property
// from the object prototype.
Object.defineProperty(this, name, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
value: value.bind(this, 'a', 'b'),
});
return this[name];
};
}
相关文章:
- 从实例方法调用实例方法
- Javascript:在对象实例方法上使用apply()方法失败
- 对象中的setInterval出现问题's方法
- 我将如何创建一个带有私有变量的实例方法
- 用javascript在实例方法中实例化对象
- 绑定实例方法与包装匿名函数
- 如何在猫鼬.js子文档数组中定义实例方法
- 如何根据所选选项调用实例方法
- 如何在匿名函数中调用实例方法
- 在续集中使用实例方法
- 如何将实例方法添加到帆中的所有模型.js
- 如何在 Javascript 中同时拥有静态方法和实例方法
- 使用木偶.js访问生态模板中的实例方法
- 在 JavaScript 中修饰实例方法时出现问题
- 在Javascript中使用寄生继承,是否可以实现内省实例方法
- 使用私有实例方法实现 TS/JS 装饰器
- ES6+React组件实例方法
- 更改<对象>.原型的实例方法(通过上下文)
- 用于区分节点JS中模块/实例/方法变量的命名约定
- 访问实例方法时出现的JavaScript OO问题