Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between 'call/apply' and 'bind' [duplicate]

var obj = {    x: 81,    getX: function() {       console.log( this.x)     } }; var getX = obj.getX.bind(obj);//use obj as 'this'; getX();//81 var getX = function(){   obj.getX.apply(obj);  } getX();//also 81 

The use of bind and call/apply look very similar, I want to know what's the difference between them.The two getX Function above is the same?

like image 769
bennyrice Avatar asked Mar 28 '13 09:03

bennyrice


People also ask

What is the difference between call apply and bind?

Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.

What is the fundamental difference between call () and apply () method?

Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function.

What is a bind call?

The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.

Which is faster call or apply?

So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.


2 Answers

bind returns a function which will act like the original function but with this predefined. It is usually used when you want to pass a function to an event handler or other async callback.

call and apply will call a function immediately letting you specify both the value of this and any arguments the function will receive.

Your second example defines an anonymous function which calls apply. This is a common pattern; bind provides a standard implementation of that which allows you to do it with a simple function call (thus being quicker and easier to write).

like image 60
Quentin Avatar answered Sep 21 '22 11:09

Quentin


.call() - calls the same function with the specified arguments

.apply() - calls the same function with the arguments specified in an array

.bind() - creates a new function with the same function body, with a preset value of this (the first argument) and returns that function.

In all cases, the first argument is used as the value of this inside the function.

like image 29
techfoobar Avatar answered Sep 21 '22 11:09

techfoobar