What is the difference between call and apply?

2018-12-31 01:30发布

What is the difference between using call and apply to invoke a function?

var func = function() {
  alert('hello!');
};

func.apply(); vs func.call();

Are there performance differences between the two aforementioned methods? When is it best to use call over apply and vice versa?

20条回答
千与千寻千般痛.
2楼-- · 2018-12-31 02:13

Call and apply both are used to force the this value when a function is executed. The only difference is that call takes n+1 arguments where 1 is this and 'n' arguments. apply takes only two arguments, one is this the other is argument array.

The advantage I see in apply over call is that we can easily delegate a function call to other function without much effort;

function sayHello() {
  console.log(this, arguments);
}

function hello() {
  sayHello.apply(this, arguments);
}

var obj = {name: 'my name'}
hello.call(obj, 'some', 'arguments');

Observe how easily we delegated hello to sayHello using apply, but with call this is very difficult to achieve.

查看更多
孤独寂梦人
3楼-- · 2018-12-31 02:15

Summary:

Both call() and apply() are methods which are located on Function.prototype. Therefore they are available on every function object via the prototype chain. Both call() and apply() can execute a function with a specified value of the this.

The main difference between call() and apply() is the way you have to pass in arguments into it. In both call() and apply() you pass as a first argument the object you want to be the value as this. The other arguments differ in the following way:

  • With call() you have to put in the arguments normally (starting from the second argument)
  • With apply() you have to pass in array of arguments.

Example:

let obj = {
  val1: 5,
  val2: 10
}

const summation = function (val3, val4) {
  return  this.val1 + this.val2 + val3 + val4;
}

console.log(summation.apply(obj, [2 ,3]));
// first we assign we value of this in the first arg
// with apply we have to pass in an array


console.log(summation.call(obj, 2, 3));
// with call we can pass in each arg individually

Why would I need to use these functions?

The this value can be tricky sometimes in javascript. The value of this determined when a function is executed not when a function is defined. If our function is dependend on a right this binding we can use call() and apply() to enforce this behaviour. For example:

var name = 'unwantedGlobalName';

const obj =  {
  name: 'Willem',
  sayName () { console.log(this.name);}
}


let copiedMethod = obj.sayName;
// we store the function in the copiedmethod variable



copiedMethod();
// this is now window, unwantedGlobalName gets logged

copiedMethod.call(obj);
// we enforce this to be obj, Willem gets logged

查看更多
登录 后发表回答