我一直在玩meinization的概念,并有明显不同的实现。我把这个在一起,它似乎很好地工作:为什么需要应用于记忆功能?
Function.prototype.memoized = function(a) {
debugger
if (typeof cache === "undefined") cache = [];
if (cache[a]) {
return cache[a];
} else {
cache[a] = this(a);
return cache[a];
}
}
Function.prototype.memoize=function() {
t=this;
return function() {
// Resig seems to use this:
return t.memoized.apply(t,arguments);
// why not simple this:
//return t.memoized(arguments[0]);
}
}
myTest = (function fibonacci(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}).memoize();
console.log(myTest(2));
我的问题是,为什么却在一些实现我看到 return t.memoized.apply(t,arguments);
而不是简单的return t.memoized(arguments[0]);
的proptotype.memoize
里面?除了传递多个未被使用的参数之外,我看不到任何优势。我有没有优势apply
?
编辑:
更新的代码,我相信这需要照顾的重大问题,使缓存为全球的窗口(我在想什么?),而不是memoizing自身递归调用斐波那契数。我的实施还有其他主要问题吗?
Function.prototype.memoized = function(a) {
if (typeof this.cache === "undefined") this.cache = [];
if (this.cache[a]) {
return this.cache[a];
} else {
this.cache[a] = this(a);
return this.cache[a];
}
}
Function.prototype.memoize=function() {
t=this;
return function() {
//return t.memoized.apply(t,arguments);
return t.memoized(arguments[0]);
}
}
myTest = (function fibonacci(n) {
//return a * 3;
return n < 2 ? n : fibonacci.memoized(n - 1) + fibonacci.memoized(n - 2);
}).memoize();
console.log(myTest(2));
顺便说一句,这是学习我的经验和做纯粹是为了好玩,它不是转让或任何类似的单向关系。
使用'窗口[“缓存”] === undefined'取代'typeof' –
使用'apply'使memoize的功能更多通用的。所以任何数量的参数都可以传递给包装函数。例如,如果您想记忆一个可能需要可变数量参数的add函数。我不明白为什么当通用解决方案稍微复杂时,你会使用't.memoized(arguments [0])'。 – SimpleJ