Why invoke “apply” instead of calling function directly?

后端 未结 5 1051
清歌不尽
清歌不尽 2020-12-31 09:56

When looking at the source code for raphael or g.raphael or other libraries I\'ve noticed the developer does something like this:

var val = Math.max.apply(Ma         


        
5条回答
  •  醉话见心
    2020-12-31 10:11

    .apply is often used when the intention is to invoke a variadic function with a list of argument values, e.g.

    The Math.max([value1[,value2, ...]]) function returns the largest of zero or more numbers.

    Math.max(10, 20); // 20
    Math.max(-10, -20); // -10
    Math.max(-10, 20); // 20
    

    The Math.max() method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.

    Math.max.apply(null, [10, 20]); // 20
    Math.max.apply(null, [-10, -20]); // -10
    Math.max.apply(null, [-10, 20]); // 20
    

    However, as of the ECMAScript 6 you can use the spread operator:

    The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

    Math.max(...[10, 20]); // 20
    Math.max(...[-10, -20]); // -10
    Math.max(...[-10, 20]); // 20
    

    When calling a function using the variadic operator, you can even add additional values, e.g.

    Math.max(...[10, 20], 50); // 50
    Math.max(...[-10, -20], 50); // 50
    

提交回复
热议问题