我正在使用decorator函数,我不想在这里使用bind
来传递this
值,相反,我想使用包装函数并在那里执行代码。但是我面对这个错误->Uncaught RangeError: Maximum call stack size exceeded
这是代码:
let math = {
multi(n, type) {
if(type == 'double') {
this.printSomething(n * 2);
}
else if (type == 'triple') {
this.printSomething(n * 3);
}
},
printSomething(result) {
console.log(result);
}
};
function cachingDecorator(func) {
let cache = new Map();
return function(n, type) {
if(cache.has(n))
return cache.get(n);
let result = func(n, type);
cache.set(n, result);
return result;
};
};
math.multi = cachingDecorator((n, type) => math.multi(n, type));
math.multi(10, 'double');
虽然我使用了Chrome开发工具,但我无法解决这个问题。
我知道出现这个错误是因为存在递归。但是在哪里呢?
问题是您将math.multi
重新分配到缓存版本,然后它的缓存版本在此处使用重新分配的值:
math.multi = cachingDecorator((n, type) => math.multi(n, type));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^
相反,你需要记住并使用原件:
const originalMulti = math.multi;
math.multi = cachingDecorator((n, type) => originalMulti.call(math, n, type));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^
注意,我必须使用.call(math
来确保this
是正确的,因为我将math.multi
复制到了一个变量;稍后直接调用它并不能正确设置CCD_ 8。
实例:
let math = {
multi(n, type) {
if(type == 'double') {
this.printSomething(n * 2);
}
else if (type == 'triple') {
this.printSomething(n * 3);
}
},
printSomething(result) {
console.log(result);
}
};
function cachingDecorator(func) {
let cache = new Map();
return function(n, type) {
if(cache.has(n))
return cache.get(n);
let result = func(n, type);
cache.set(n, result);
return result;
};
}
const originalMulti = math.multi;
math.multi = cachingDecorator((n, type) => originalMulti.call(math, n, type));
math.multi(10, 'double');