What is the difference between call and apply?

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

    A well explained by flatline. I just want to add a simple example. which makes it easy to understand for beginners.

    func.call(context, args1 , args2 ); // pass arguments as "," saprated value
    
    func.apply(context, [args1 , args2 ]);   //  pass arguments as "Array"
    

    we also use "Call" and "Apply" method for changing reference as defined in code below

        let Emp1 = {
            name: 'X',
            getEmpDetail: function (age, department) {
                console.log('Name :', this.name, '  Age :', age, '  Department :', department)
            }
        }
        Emp1.getEmpDetail(23, 'Delivery')
    
        // 1st approch of chenging "this"
        let Emp2 = {
            name: 'Y',
            getEmpDetail: Emp1.getEmpDetail
        }
        Emp2.getEmpDetail(55, 'Finance')
    
        // 2nd approch of changing "this" using "Call" and "Apply"
        let Emp3 = {
            name: 'Z',
        }
    
        Emp1.getEmpDetail.call(Emp3, 30, 'Admin')        
    // here we have change the ref from **Emp1 to Emp3**  object
    // now this will print "Name =  X" because it is pointing to Emp3 object
        Emp1.getEmpDetail.apply(Emp3, [30, 'Admin']) //

    0 讨论(0)
  • 2020-11-21 07:46

    K. Scott Allen has a nice writeup on the matter.

    Basically, they differ on how they handle function arguments.

    The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."

    So:

    // assuming you have f
    function f(message) { ... }
    f.call(receiver, "test");
    f.apply(receiver, ["test"]);
    
    0 讨论(0)
  • 2020-11-21 07:47

    Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-21 07:50

    While this is an old topic, I just wanted to point out that .call is slightly faster than .apply. I can't tell you exactly why.

    See jsPerf, http://jsperf.com/test-call-vs-apply/3


    [UPDATE!]

    Douglas Crockford mentions briefly the difference between the two, which may help explain the performance difference... http://youtu.be/ya4UHuXNygM?t=15m52s

    Apply takes an array of arguments, while Call takes zero or more individual parameters! Ah hah!

    .apply(this, [...])

    .call(this, param1, param2, param3, param4...)

    0 讨论(0)
提交回复
热议问题