【发布时间】:2015-07-31 12:42:31
【问题描述】:
我已经阅读了 "How to implement a typescript decorator?" 和多个来源,但有些东西我无法用装饰器做。
class FooBar {
public foo(arg): void {
console.log(this);
this.bar(arg);
}
private bar(arg) : void {
console.log(this, "bar", arg);
}
}
如果我们调用函数foo:
var foobar = new FooBar();
foobar.foo("test");
对象FooBar被console.log(this);在foo中记录到控制台
console.log(this, "bar", arg); 将字符串 "FooBar {foo: function, bar: function} bar test" 记录在控制台中,bar。
现在让我们使用装饰器:
function log(target: Function, key: string, value: any) {
return {
value: (...args: any[]) => {
var a = args.map(a => JSON.stringify(a)).join();
var result = value.value.apply(this, args); // How to avoid hard coded this?
var r = JSON.stringify(result);
console.log(`Call: ${key}(${a}) => ${r}`);
return result;
}
};
}
我们使用相同的功能,但装饰:
class FooBar {
@log
public foo(arg): void {
console.log(this);
this.bar(arg);
}
@log
private bar(arg) : void {
console.log(this, "bar", arg);
}
}
我们像以前一样调用foo:
var foobarFoo = new FooBar();
foobarFooBar.foo("test");
对象Window 被console.log(this); 登录到控制台foo
并且bar 永远不会被foo 调用,因为this.bar(arg); 会导致Uncaught TypeError: this.bar is not a function。
问题在于log 装饰器内部的硬编码this:
value.value.apply(this, args);
如何保存原来的this 值?
【问题讨论】:
标签: javascript typescript decorator ecmascript-2016