What is the difference between call and apply?

前端 未结 24 2398
太阳男子
太阳男子 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 08:03

    Call and apply both are used to force the this value when a function is executed. The only difference is that call takes n+1 arguments where 1 is this and 'n' arguments. apply takes only two arguments, one is this the other is argument array.

    The advantage I see in apply over call is that we can easily delegate a function call to other function without much effort;

    function sayHello() {
      console.log(this, arguments);
    }
    
    function hello() {
      sayHello.apply(this, arguments);
    }
    
    var obj = {name: 'my name'}
    hello.call(obj, 'some', 'arguments');
    

    Observe how easily we delegated hello to sayHello using apply, but with call this is very difficult to achieve.

提交回复
热议问题