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

2016-10-13 23:19发布

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么

1条回答

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

一周热门 更多>