我读过了“如何实现打字稿装饰器?”和多个来源,但有些事情我无法使用装饰器完成。
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);
in foo
字符串"FooBar {foo: function, bar: function} bar test"
通过以下方式登录到控制台console.log(this, "bar", arg);
in 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);
in foo
And bar
永远不会被调用foo
因为this.bar(arg);
causes Uncaught TypeError: this.bar is not a function
.
问题是硬编码this
在 - 的里面log
装饰器:
value.value.apply(this, args);
怎样才能保存原来的this
value?