You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于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 obj is 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 of obj. In JavaScript, when a function is called as an object method, this is bound to the object itself.
  • So this.value directly references obj.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 = 2 variable from the outer IIFE’s scope (thanks to JavaScript closures).
  • Crucially, this IIFE doesn’t use this at all—so it doesn’t care about the object’s own value: 1 property. It just grabs the value from the surrounding scope, returns 2, and that value is assigned directly to obj.getValue.
Key Takeaways

The main differences come down to two critical concepts:

  • this Binding: When a function is called as an object method, this points to the object. If you skip this, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:56:31