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.
His answer is coherent but I believe that in this case better fit the lime() as said Sergio
– Felipe Coelho