我已经在javascript上下文中阅读了很多有关此的内容,并一直在尝试理解装饰器代码。每当我查看装饰器代码时,例如下面的代码,即使输入函数未对“ this”进行任何引用,它也始终将此输入函数应用于“ this”。这是为什么?是否有必要始终在装饰器中将函数应用于“ 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();