这个将变量赋给返回函数值的 Javascript 模式的专有名称是什么?
// array with a ton of random values.
var once = (function(){
var i = 10000, arr = [];
while(i){
arr.push( Math.random() * i );
i--;
}
arr = arr.toString();
return (function(){
return arr;
}());
}());
编辑 - 一个更好的例子:
var once = (function(){
// Only run a really expensive operation once...
var i = 10000, arr = [], x;
while(i){
arr.push( Math.random() * i );
i--;
}
arr = arr.toString();
x = parseFloat(arr.toString());
// then return the result of another function
return function(){
return x * (Math.random() * 10);
};
}());
$(window).resize(function(){
console.info(once());
});
最佳答案
我相信您正在寻找 memoization .
In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.
...
A memoized function "remembers" the results corresponding to some set of specific inputs. Subsequent calls with remembered inputs return the remembered result rather than recalculating it, thus eliminating the primary cost of a call with given parameters from all but the first call made to the function with those parameters.
关于javascript - 带有分配函数返回值的变量的 javascript 模式的名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9848412/