理解函数中的this关键字:两段箭头函数代码差异原因咨询
Great question! Let's break this down step by step, starting with the key quirk of arrow functions that's driving this behavior: arrow functions don't have their own this binding. Instead, they inherit the this value from the outer scope they were defined in—this is non-negotiable, no matter how you call the arrow function.
Let's Look at Your First Snippet
let bar = () => { let x = 5; console.log(this.x) } bar();
Here, you declare a local variable x with let x = 5. This variable lives only inside the arrow function's scope—it has zero connection to the this value. Since the arrow function inherits this from the outer scope (in a browser, that's the global window object; in Node.js modules, it's module.exports), this.x is looking for an x property on that outer object.
Since you never defined an x property on that outer object, console.log(this.x) will output undefined (or throw an error if you're in strict mode). That's probably why you felt it "wasn't running correctly."
Now Your Second Snippet
let bar = () => { this.x = 5; console.log(this.x) } bar();
Here, you're directly assigning this.x = 5, which adds an x property to the outer scope's this object (like window.x in the browser). When you then log this.x, you're just reading that property you just created—so it outputs 5, which feels like it's "working correctly."
Correcting Your Understanding
You're half-right here: local variables declared with let/const/var inside a function never automatically become properties of any object—they're only accessible within the function's scope. But there's a critical mistake in your reasoning:
Arrow functions don't have their own "function object" that this points to. The this in your arrow function isn't referring to the arrow function itself—it's referring to the this from the scope where the arrow function was defined. When you do this.x = 5, you're attaching that x to that outer scope's object (like the global window), not the arrow function.
To make this clearer, let's compare with a regular function (which does have its own this binding):
// Regular function function regularBar() { let x = 5; console.log(this.x); // In non-strict mode, this points to window—logs undefined this.x = 6; console.log(this.x); // Logs 6, because we just added x to window } regularBar(); // Arrow function const arrowBar = () => { let x = 5; console.log(this.x); // Inherits window as this—logs undefined (if no prior x) this.x = 7; console.log(this.x); // Logs 7, since we added x to window } arrowBar();
Final Takeaways
- Local function variables and
thisproperties are completely separate—local variables never get attached to objects automatically. - Arrow functions don't have their own
this; they borrow it from the outer scope. Anythisassignments in an arrow function affect that outer scope's object, not the arrow function itself.
内容的提问来源于stack exchange,提问作者J Seabolt

