Bind Javascript

Asked

Viewed 1,883 times

7

I wrote this code as a study for understanding bind. I create a method on an object and try to call it by changing Scope to another object.

let car = {
  sound: 'Vrrrrummm',
  startEngine: function() {
    console.log(this.sound)
  }
}

let bike = {
  sound: "Papapapapapapraprap"
}

car.startEngine.bind(bike)

Help me solve or explain if I have misunderstood the concept of bind

3 answers

6

Your code is right, just missed you invoke the method. For this I added the invocation (()) at the end of your code:

inserir a descrição da imagem aqui

Following is the functional version:

let car = {
  sound: 'Vrrrrummm',
  startEngine: function() {
    console.log(this.sound)
  }
}

let bike = {
  sound: "Papapapapapapraprap"
}

car.startEngine.bind(bike)()

  • His answer is coherent but I believe that in this case better fit the lime() as said Sergio

6


When you use the .bind() it generates a new function with a new execution context. The .bind() alone does not run/invoke the function. I think you intend to use the .call() or the .apply() in this case, to invoke the function with a new execution context.

Take a look at this example with .call():

let car = {
  sound: 'Vrrrrummm',
  startEngine: function() {
    console.log(this.sound)
  }
}

let bike = {
  sound: "Papapapapapapraprap"
}

car.startEngine.call(bike);

To do the same with .bind() you’d have to do something like this:

let car = {
  sound: 'Vrrrrummm',
  startEngine: function() {
    console.log(this.sound)
  }
}

let bike = {
  sound: "Papapapapapapraprap"
}

let minhaFuncao = car.startEngine.bind(bike);
minhaFuncao();

So you create a new function and then you run that function.

Note:

Context and scope are different things. You can give a look at this other response, but basically context is the this when the function runs, scope is that variables outside the function are accessible to the function.

  • 1

    Very good. The bind only changes the context, so the line Let myFuncao = car.startEngine.bind(bike) does nothing. Thank you, it helped a lot.

2

Function#bind(instância, ...argumentos) returns a function, which calls another function, with instance and arguments memorized (including that can still be passed + arguments when calling it).

It would have been easier to have used Function#call(instância, argumentos) in that context:

car.startEngine.call(bike)

(This makes the this a new scope of a function is a reference to the bike.)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.