向我解释我的_.memoize函数是如何逐步工作的

时间:2016-07-04 18:34:41

标签: javascript underscore.js

_.memoize = function(func) { //declare memoize function that takes in a function
    var memorized = {} //declare an object literal which will store each function call and result
    return function () { //not sure why I need to return an anonymous function
      var memo = Array.prototype.slice.apply(arguments, arguments) //Use Array method of slice on the arguments array of the func function save it to variable memo
      if(memorized[memo]){ //if the key of arguments exists in the memoized object
        return memorized[memo]; //return the associated value
      } else { //if the key of arguments does not exist in the object
        return memorized[memo] = func.apply(null, arguments); //call func with the arguments and save the result into the memoized object with the argument array as a key
      }
    }
  };

我试着逐行解释,看看我的思想和知识是否正确。

我想我唯一的问题是为什么我们需要在函数内部进行匿名函数调用?另外,如何知道我们正在谈论的论点。

0 个答案:

没有答案