What is the difference between call and apply?

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

    Here's a small-ish post, I wrote on this:

    http://sizeableidea.com/call-versus-apply-javascript/

    var obj1 = { which : "obj1" },
    obj2 = { which : "obj2" };
    
    function execute(arg1, arg2){
        console.log(this.which, arg1, arg2);
    }
    
    //using call
    execute.call(obj1, "dan", "stanhope");
    //output: obj1 dan stanhope
    
    //using apply
    execute.apply(obj2, ["dan", "stanhope"]);
    //output: obj2 dan stanhope
    
    //using old school
    execute("dan", "stanhope");
    //output: undefined "dan" "stanhope"
    

提交回复
热议问题