装饰器为什么必须将(this)应用于函数

我已经在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);
jingleee 回答:装饰器为什么必须将(this)应用于函数

当被调用为某些对象的方法时,为包装函数提供正确的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传递给原始方法,否则它将无法解析{{ 1}}。显然,如果原始函数不以任何方式使用this.property,则仍然没有必要,仍然是始终使用this编写装​​饰器的好习惯,以便可以在任何上下文中使用它们

本文链接:https://www.f2er.com/3091085.html

大家都在问