What is the difference between call and apply?

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

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

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


        
24条回答
  •  旧时难觅i
    2020-11-21 07:54

    Let me add a little detail to this.

    these two calls are almost equivalent:

    func.call(context, ...args); // pass an array as list with spread operator
    
    func.apply(context, args);   // is same as using apply
    

    There’s only a minor difference:

    • The spread operator ... allows passing iterable args as the list to call.
    • The apply accepts only array-like args.

    So, these calls complement each other. Where we expect an iterable, call works, where we expect an array-like, apply works.

    And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but apply will probably be faster because most JavaScript engines internally optimize it better.

提交回复
热议问题