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

标签 javascript typescript this decorator

我在 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/

相关文章:

javascript - 访问绑定(bind)到底层类的 DOM 节点和函数

javascript - 调整表头大小以匹配 ASP.net GridView 生成的表体

javascript - 当对象不再被引用时clearInterval?

根据要求分配类(class)的算法

typescript - 语法错误: Use of const in strict mode with Riot/TypeScript

java - 我的代码中的 'this' 关键字指的是什么?

javascript - 单击 html 文本输入的顶部或底部边缘时出现奇怪的光标放置行为

javascript - 如何让浏览器缓存一个https站点的css和js文件?

javascript - admin.firestore.Timestamp.now() 和 admin.firestore.FieldValue.serverTimestamp() 有什么区别?

javascript - 处理 'this' 变化的最佳方式