What is the difference between call and apply?

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

    I'd like to show an example, where the 'valueForThis' argument is used:

    Array.prototype.push = function(element) {
       /*
       Native code*, that uses 'this'       
       this.put(element);
       */
    }
    var array = [];
    array.push(1);
    array.push.apply(array,[2,3]);
    Array.prototype.push.apply(array,[4,5]);
    array.push.call(array,6,7);
    Array.prototype.push.call(array,8,9);
    //[1, 2, 3, 4, 5, 6, 7, 8, 9] 
    

    **details: http://es5.github.io/#x15.4.4.7*

提交回复
热议问题