简体   繁体   中英

Why calling a function inside another function doesn't work?

var mult = (function(){
    var cache = {};
    var calculate = function(){
        var a = 1;
        for(var i = 0, l = arguments.length; i < l; i++){
          a = a * arguments[i];
        }
        return a;
    }

    return function(){
      return calculate(arguments);
    }
})();

console.log(mult(1, 2));

Above is my code, I expect the mult function will give me value 2, but instead it outputs NaN. I changed the line calculate(arguments) to caculate.apply(null, arguments) and it worked. I don't know why the old code doesn't work? Why do I need to use apply in this case? What does null represent here?

Your calculate function wants separate arguments, but you passed in an array 1 . Using .apply spreads the content of the array for you.

1 Technically an array-like arguments object that does not inherit from Array .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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