Javascript call() & apply() vs bind()? Javascript call() & apply() vs bind()? arrays arrays

Javascript call() & apply() vs bind()?


Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

I do this a lot:

function MyObject(element) {    this.elm = element;    element.addEventListener('click', this.onClick.bind(this), false);};MyObject.prototype.onClick = function(e) {     var t=this;  //do something with [t]...    //without bind the context of this function wouldn't be a MyObject    //instance as you would normally expect.};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

A simple, naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {    var fn = this;    return function() {        fn.apply(ctx, arguments);    };};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

Hope this helps.


They all attach this into function (or object) and the difference is in the function invocation (see below).

call attaches this into function and executes the function immediately:

var person = {    name: "James Smith",  hello: function(thing) {    console.log(this.name + " says hello " + thing);  }}person.hello("world");  // output: "James Smith says hello world"person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"

bind attaches this into function and it needs to be invoked separately like this:

var person = {    name: "James Smith",  hello: function(thing) {    console.log(this.name + " says hello " + thing);  }}person.hello("world");  // output: "James Smith says hello world"var helloFunc = person.hello.bind({ name: "Jim Smith" });helloFunc("world");  // output: Jim Smith says hello world"

or like this:

...    var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");helloFunc();  // output: Jim Smith says hello world"

apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:

function personContainer() {  var person = {       name: "James Smith",     hello: function() {       console.log(this.name + " says hello " + arguments[1]);     }  }  person.hello.apply(person, arguments);}personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"                                     


Answer in SIMPLEST form

  • Call invokes the function and allows you to pass in arguments one byone.
  • Apply invokes the function and allows you to pass in argumentsas an array.
  • Bind returns a new function, allowing you to pass in athis array and any number of arguments.

Apply vs. Call vs. Bind Examples

Call

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say(greeting) {    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);}say.call(person1, 'Hello'); // Hello Jon Kupermansay.call(person2, 'Hello'); // Hello Kelly King

Apply

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say(greeting) {    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);}say.apply(person1, ['Hello']); // Hello Jon Kupermansay.apply(person2, ['Hello']); // Hello Kelly King

Bind

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};var person2 = {firstName: 'Kelly', lastName: 'King'};function say() {    console.log('Hello ' + this.firstName + ' ' + this.lastName);}var sayHelloJon = say.bind(person1);var sayHelloKelly = say.bind(person2);sayHelloJon(); // Hello Jon KupermansayHelloKelly(); // Hello Kelly King

When To Use Each

Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.

I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.

Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.

Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon or helloKelly. We can also use it for events like onClick where we don’t know when they’ll be fired but we know what context we want them to have.

Reference: codeplanet.io