Bind JavaScript

6

I wrote this code as a study for the understanding of bind. I create a method in an object and try to call it by changing the 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

    
asked by anonymous 15.11.2016 / 06:07

3 answers

6

When you use .bind() it generates a new function with a new execution context. The .bind() by itself does not run / invoke the function. I think you want to use .call() or .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 would 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 run that function.

Note:

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

    
15.11.2016 / 06:52
6

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

Followingthefunctionalversion:

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

let bike = {
  sound: "Papapapapapapraprap"
}

car.startEngine.bind(bike)()
    
15.11.2016 / 06:51
2

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

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

car.startEngine.call(bike)

(This causes the this of a new scope of a function to be a reference to bike .)

    
15.11.2016 / 13:06