为什么装饰器必须将(this)应用于函数
Why do decorators have to apply(this) to a function
我在 javascript 上下文中阅读了很多相关内容,并一直在尝试理解装饰器代码。每当我查看装饰器代码时,如下所示,它总是将此输入函数应用于 'this',即使输入函数没有对 '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();
这里,我们的修饰函数调用时this
等于t
,必须把这个this
传给原来的方法,否则无法解析this.property
。显然,如果原始函数不以任何方式使用 this
,则没有必要这样做,不过,始终使用 apply
编写装饰器是一个好习惯,这样它们就可以在任何上下文中使用.
我在 javascript 上下文中阅读了很多相关内容,并一直在尝试理解装饰器代码。每当我查看装饰器代码时,如下所示,它总是将此输入函数应用于 'this',即使输入函数没有对 '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();
这里,我们的修饰函数调用时this
等于t
,必须把这个this
传给原来的方法,否则无法解析this.property
。显然,如果原始函数不以任何方式使用 this
,则没有必要这样做,不过,始终使用 apply
编写装饰器是一个好习惯,这样它们就可以在任何上下文中使用.