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.