What is the difference between call and apply?

前端 未结 24 1668
太阳男子
太阳男子 2020-11-21 07:12

What is the difference between using call and apply to invoke a function?

var func = function() {
  alert(\'hello!\');
};
         


        
24条回答
  •  执笔经年
    2020-11-21 07:46

    K. Scott Allen has a nice writeup on the matter.

    Basically, they differ on how they handle function arguments.

    The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

    So:

    // assuming you have f
    function f(message) { ... }
    f.call(receiver, "test");
    f.apply(receiver, ["test"]);
    

提交回复
热议问题