【发布时间】:2019-11-16 07:39:09
【问题描述】:
我在 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' 进行任何引用" - 但如果这样做了呢?关键是装饰者无法知道,所以它总是要安全行事。
标签: javascript typescript this decorator