What is the difference between call and apply?

前端 未结 24 1706
太阳男子
太阳男子 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:47

    It is useful at times for one object to borrow the function of another object, meaning that the borrowing object simply executes the lent function as if it were its own.

    A small code example:

    var friend = {
        car: false,
        lendCar: function ( canLend ){
          this.car = canLend;
     }
    
    }; 
    
    var me = {
        car: false,
        gotCar: function(){
          return this.car === true;
      }
    };
    
    console.log(me.gotCar()); // false
    
    friend.lendCar.call(me, true); 
    
    console.log(me.gotCar()); // true
    
    friend.lendCar.apply(me, [false]);
    
    console.log(me.gotCar()); // false
    

    These methods are very useful for giving objects temporary functionality.

提交回复
热议问题