繁体   English   中英

Javascript:如何获取function.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()函数应返回一个函数,该函数在被调用时将检查是否已经计算了给定参数的结果,并在可能的情况下返回该值。

为什么需要带有索引的对象。 只需存储结果/密钥。

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 

您在寻找什么叫做记忆

请参阅: 在JavaScript中实现记忆

这是一个例子:

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, 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对象引用中是否存在索引。 否则,您应该使用其他范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM