优艾设计网

[JavaScript] 装饰器修改函数时怎么保证this的指向不变?

优艾设计网 https://www.uibq.com 2023-06-12 07:54 出处:网络 作者:磨皮美容教程
memorizerDecorator(resolver?: Function) { let cache = new Map<any, any>(); resolver = resolver || function (args: Array<any>) { return args[0]; };return (target, propertyKey: string, descr

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: Func优艾设计网_PS交流tion = 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么


u_101441265 优艾设计网_设计百科 5小时前

bind?es6 的()=>{}是自动bind的吧。。。


0

精彩评论

暂无评论...
验证码 换一张
取 消