Javascript:如何获取函数.apply()的键
Javascript: How to get key of function.apply()
我正在尝试缓存'func.apply(this,func)'值,以便以后可以查找它,而不是再次运行该函数。问题是我不知道怎么用或者用什么作为钥匙。
有没有一种方法可以分配一个稍后可以查找的函数的键?
代码示例:
var m = function(func) {
var cached = {};
return function() {
var key = ''; // how do I get or create the key of func.apply(this, func)?
if (cached[key]) {
return cached[key];
}
cached[key] = func.apply(this, arguments);
return cached[key];
};
};
m()函数应该返回一个函数,当调用该函数时,该函数将检查它是否已经计算出给定参数的结果,并在可能的情况下返回该值。
您正在寻找的是Memoization
请参阅:在JavaScript 中实现Memoization
下面是一个例子:
var myFunction = (function() {
'use strict';
var functionMemoized = function() {
// set the argumensts list as a json key
var cacheKey = JSON.stringify(Array.prototype.slice.call(arguments));
var result;
// checks whether the property was cached previously
// also: if (!(cacheKey in functionMemoized.cache))
if (!functionMemoized.cache.hasOwnProperty(cacheKey)) {
// your expensive computation goes here
// to reference the paramaters passed, use arguments[n]
// eg.: result = arguments[0] * arguments[1];
functionMemoized.cache[cacheKey] = result;
}
return functionMemoized.cache[cacheKey];
};
functionMemoized.cache = {};
return functionMemoized;
}());
为什么需要一个带索引的对象。只需存储结果/密钥。
var m = function(func) {
var result=null;
return function() {
if (result===null) {
result = func.apply(this, arguments);
}
return result;
}
};
但我不确定这是你想要的。如果函数基于参数返回不同的值,则需要使用基于参数的键。
var m = function(func) {
var results = {};
return function() {
var key = [].slice.call(arguments).join("-");
if (results[key]===undefined) {
results[key] = func.apply(this, arguments);
}
return results[key];
}
};
var multiply = function (a,b) {
return a * b;
}
var mult = m(multiply);
console.log(mult(2,5)); //runs calculation
console.log(mult(2,5)); //uses cache
如果您将函数的值作为字符串发送,您可以使用它作为索引,只需进行一次小的修改
var m = function(func, scope) {
return function() {
var cached = {};
var index = func; // how do I get or create the index of func.apply(this, func)?
scope = scope || this;
if (!cached[index]) {
func = scope[func]; //Get the reference to the function through the name
cached[index] = func.apply(this, func);
}
return cached[index];
};
};
这取决于索引是否存在于this
对象引用中。否则,您应该使用不同的作用域。
相关文章:
- Javascript:如何获取函数.apply()的键
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何通过 Function.prototype.apply() 更改调用函数的参数
- 通过fn.apply或fn.bind将函数传递给setTimeout
- 了解窗口调整大小事件与 scope.$apply 与函数$watch
- 节点redis't喜欢函数.apply()
- 未捕获的类型错误:hook.apply不是在react路由器中使用onEnter时的函数
- 函数式编程 - .bind.apply for curry function.
- JS:.apply(null,arguments)——为什么我的函数被调用一次,而console.log被调用多次
- 函数 (){ 返回 fn.apply(me, arguments); } 作为回调
- 将函数绑定到baz后调用fn.apply(bar,[])
- 使用数组-apply()中的参数调用函数,但不使用上下文参数
- 类型错误: $scope.apply 不是一个函数
- $.when.apply.done 不执行异步函数
- node.js 使用 function.prototype.apply 执行的泛型函数
- KNOCKOUT.js问题:“H.apply不是一个函数.(在'h.apply(e,r)'中,'
- 如果不在Angular.js中使用$apply(),我该如何编写此函数
- 更新'这'当返回用.apply()调用的函数时,从回调
- Uncatch TypeError: pos.apply 不是 showtooltip() 方法中的函数
- Ajax 调用和函数.apply infinite loop.