下划线从头开始记忆

underscore memoize from scratch

在学习underscore memoize时,我不理解这行: "var argString = Array.prototype.join.call(arguments,"_")."我知道它正在创建一个参数字符串,但它如何适用于此?

_.memoize = function(func) {
    var output  = {}; 
    return function(){
        var argString = Array.prototype.join.call(arguments,"_");       
        if (output[argString] === undefined){ 
            output[argString] = func.apply(this, arguments); 
        }
        return output[argString];
    };
};

在上面的代码中,最初创建了一个名称为 output 的对象。

接下来,根据参数创建对象的键。

示例:考虑一个函数,

function x(a,b,c){
   // argument will be in an array form, but not an Array actually
   console.log(argument) // will give array like structure.
}

现在,使用 Array.prototype.join.call(arguments,"_"); 根据参数生成动态密钥。

接下来,

if (output[argString] === undefined){ 
        output[argString] = func.apply(this, arguments); 
       }

这将检查,动态生成的密钥是否存在于 output 对象中,

如果存在,它将 return 不调用函数的值,否则它将调用该函数并将键和值缓存在输出对象中。

希望你明白这背后的逻辑。