What is the difference between call and apply?

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

    To answer the part about when to use each function, use apply if you don't know the number of arguments you will be passing, or if they are already in an array or array-like object (like the arguments object to forward your own arguments. Use call otherwise, since there's no need to wrap the arguments in an array.

    f.call(thisObject, a, b, c); // Fixed number of arguments
    
    f.apply(thisObject, arguments); // Forward this function's arguments
    
    var args = [];
    while (...) {
        args.push(some_value());
    }
    f.apply(thisObject, args); // Unknown number of arguments
    

    When I'm not passing any arguments (like your example), I prefer call since I'm calling the function. apply would imply you are applying the function to the (non-existent) arguments.

    There shouldn't be any performance differences, except maybe if you use apply and wrap the arguments in an array (e.g. f.apply(thisObject, [a, b, c]) instead of f.call(thisObject, a, b, c)). I haven't tested it, so there could be differences, but it would be very browser specific. It's likely that call is faster if you don't already have the arguments in an array and apply is faster if you do.

提交回复
热议问题