[JavaScript] 装饰器修改函数时怎么保证this的指向不变
memorizerDecorator(resolver?: Function) {
let cache = new Map<any, any>();
resolver = resolver || function (args: Array<any>) {
return args[0];
};
return (target, propertyKey: string, descriptor: PropertyDescriptor) => {
const method: Function = descriptor.value;
descriptor.value = function (...args) {
const key = resolver(args);
if (!cache.has(key)) {
cache.set(key, method.bind(target)(...args));
}
return cache.get(key);
};
descriptor.value.resetCache = () => {
cache = new Map<any, any>();
};
descriptor.value.getCache = () => {
return cache;
};
return descriptor;
};
}
class F {
w = 1;
@memorizerDecorator()
fib3(n) {
console.log(this.w);
if (n === 0 || n === 1) {
return n;
}
return this.fib3(n - 1) + this.fib3(n - 2);
}
}
修改后的方法怎么才能访问到原来的this.w么
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
bind?
es6 的()=>{}是自动bind的吧。。。
你好,你的问题解决了吗 我也遇到这个问题了 在原来的实例方法中访问不到this了
descriptor.value = function(this:any, ..._args: any[]){}
this就是class F的this