我在 javascript 上下文中阅读了很多相关内容,并尝试理解装饰器代码。每当我查看装饰器代码(如下所示)时,它总是将此输入函数应用于“this”,即使输入函数没有对“this”进行任何引用。这是为什么?是否有必要始终在装饰器中将函数应用于“this”?它还在很多地方说装饰器不能是箭头函数,因为绑定(bind)到了 this 。有人能解释为什么这会影响功能吗?
function doSomething(name) {
console.log('Hello, ' + name);
}
function loggingDecorator(wrapped) {
return function() {
console.log('Starting');
const result = wrapped.apply(this, arguments);
console.log('Finished');
return result;
}
}
const wrapped = loggingDecorator(doSomething);
最佳答案
当包装函数作为某个对象的方法调用时,这是为包装函数提供正确的 this
所必需的,请考虑:
function loggingDecorator(wrapped) {
return function () {
console.log('Starting');
//const result = wrapped() // <-- this doesn't work
const result = wrapped.apply(this, arguments); // <-- this does
console.log('Finished');
return result;
}
}
class T {
constructor() {
this.property = 42;
}
someMethod() {
console.log(this.property)
}
}
T.prototype.someMethod = loggingDecorator(T.prototype.someMethod);
t = new T;
t.someMethod();
在这里,我们的修饰函数被调用时 this
等于 t
并且必须将这个 this
向下传递给原始方法,否则它将无法解析 this.property
。显然,如果原始函数不以任何方式使用 this
,则没有必要,不过,始终使用 apply
编写装饰器是一个很好的做法,以便它们可以在任何上下文中使用。
关于javascript - 为什么装饰器必须将(this)应用于函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58888612/