Javascript:如何获取函数.apply()的键

Javascript: How to get key of function.apply()

本文关键字:函数 apply 的键 获取 何获取 Javascript      更新时间:2023-09-26

我正在尝试缓存'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对象引用中。否则,您应该使用不同的作用域。