关于JavaScript IIFE、对象的咨询:为何两段代码分别输出1和2?求学习链接
Hey there! Let’s break down these two code snippets to understand why one outputs 1 and the other 2—these are classic examples of how IIFEs (Immediately Invoked Function Expressions) interact with object scope and this binding in JavaScript.
Snippet 1 (Outputs 1)
Let’s assume this is the first code block you’re working with:
const obj = { value: 1, getValue: (function() { // This IIFE returns a function that uses `this` return function() { return this.value; }; })() }; console.log(obj.getValue()); // Logs 1
Why it outputs 1:
- The inner IIFE runs immediately when the
objis created, but all it does is return a new function (not a direct value). - When we call
obj.getValue()later, that returned function is invoked as a method ofobj. In JavaScript, when a function is called as an object method,thisis bound to the object itself. - So
this.valuedirectly referencesobj.value, which is set to 1. That’s why we see 1 in the console.
Snippet 2 (Outputs 2)
Now here’s the second snippet that outputs 2:
const obj = (function() { // This variable lives in the outer IIFE's scope let value = 2; return { value: 1, getValue: (function() { // This IIFE runs immediately and returns the outer `value` return value; })() }; })(); console.log(obj.getValue); // Logs 2
Why it outputs 2:
- The inner IIFE runs right when the object is being initialized (before we ever access
obj.getValue). - At the time this IIFE executes, it has access to the
value = 2variable from the outer IIFE’s scope (thanks to JavaScript closures). - Crucially, this IIFE doesn’t use
thisat all—so it doesn’t care about the object’s ownvalue: 1property. It just grabs thevaluefrom the surrounding scope, returns 2, and that value is assigned directly toobj.getValue.
Key Takeaways
The main differences come down to two critical concepts:
thisBinding: When a function is called as an object method,thispoints to the object. If you skipthis, the function will look for variables in its scope chain instead of object properties.- IIFE Execution Timing: IIFEs run the moment they’re defined, not later when you access a property or call a method. Their return value is fixed at initialization time.
内容的提问来源于stack exchange,提问作者faizan
相关产品推荐
相关产品推荐

