What is the difference between call and apply?

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

    From the MDN docs on Function.prototype.apply() :

    The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

    Syntax

    fun.apply(thisArg, [argsArray])
    

    From the MDN docs on Function.prototype.call() :

    The call() method calls a function with a given this value and arguments provided individually.

    Syntax

    fun.call(thisArg[, arg1[, arg2[, ...]]])
    

    From Function.apply and Function.call in JavaScript :

    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.


    Code example :

    var doSomething = function() {
        var arr = [];
        for(i in arguments) {
            if(typeof this[arguments[i]] !== 'undefined') {
                arr.push(this[arguments[i]]);
            }
        }
        return arr;
    }
    
    var output = function(position, obj) {
        document.body.innerHTML += '

    output ' + position + '

    ' + JSON.stringify(obj) + '\n
    \n

    '; } output(1, doSomething( 'one', 'two', 'two', 'one' )); output(2, doSomething.apply({one : 'Steven', two : 'Jane'}, [ 'one', 'two', 'two', 'one' ])); output(3, doSomething.call({one : 'Steven', two : 'Jane'}, 'one', 'two', 'two', 'one' ));

    See also this Fiddle.

提交回复
热议问题