问题
I have this bit of code:
const data = {
x: "Target"
}
let bar = () => {
console.log(this.x)
}
let final = bar.bind(data);
final();
This code returns undefined. Here is the same code, but with non-arrow functions:
const data = {
x: "Target"
}
let bar = function(){
console.log(this.x)
}
let final = bar.bind(data);
final();
This code works. I want to understand why the arrow function kept the binding from working. I know that they handle this differently. I know that they keep the original context in which they were called, which in this case does not include x. But does it also prevent bind() from working?
回答1:
But does it also prevent bind() from working?
Partially, because bind
returns a new function that calls the original function with a specific this
— but arrow functions don't use the this
they're called with, they completely ignore it. Instead, they close over the this
where they're defined.
bind
on an arrow function can't change the arrow's concept of this
. All it can do is its secondary feature, pre-supplying arguments:
"use strict";
function run() {
const f = (a, b, c) => {
console.log("this", this);
console.log("a", a);
console.log("b", b);
console.log("c", c);
};
const fbound = f.bind({}, 1, 2, 3);
f();
fbound();
}
run();
.as-console-wrapper {
max-height: 100% !important;£
}
回答2:
Arrow function takes precedence over bind. Whenever there are two or more different ways of setting this context, they are resolved in the following order: -arrow functions -new keyword -bind -call or apply
来源:https://stackoverflow.com/questions/50630044/javascript-binding-arrow-functions-and-bind