MST

星途 面试题库

面试题:JavaScript 复杂场景下函数 this 绑定分析

以下代码输出结果是什么?请详细说明每一步中 `this` 绑定的过程和依据。 ```javascript function Outer() { this.value = 1; function Inner() { return this.value; } return Inner(); } const result1 = new Outer(); function AnotherOuter() { this.value = 2; const innerFunc = function() { return this.value; }.bind(this); return innerFunc(); } const result2 = new AnotherOuter(); console.log(result1, result2); ```
34.7万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 分析 Outer 函数调用过程及 this 绑定
    • 当执行 const result1 = new Outer(); 时:
      • 首先,new 操作符创建一个新的空对象,这个新对象会被作为 this 绑定到 Outer 函数内部。
      • Outer 函数内部,执行 this.value = 1;,此时 this 指向新创建的对象,所以新对象拥有了属性 value 且值为 1
      • 然后定义了内部函数 Inner。当执行 return Inner(); 时,由于 Inner 函数是在非严格模式下直接调用(没有通过某个对象调用,如 obj.Inner() 这种形式),在非严格模式下,this 会默认绑定到全局对象(在浏览器环境中是 window,在 Node.js 环境中是 global)。因为全局对象没有 value 属性,所以返回 undefined。即 result1 的值为 undefined
  2. 分析 AnotherOuter 函数调用过程及 this 绑定
    • 当执行 const result2 = new AnotherOuter(); 时:
      • new 操作符创建一个新的空对象,这个新对象作为 this 绑定到 AnotherOuter 函数内部。
      • AnotherOuter 函数内部,执行 this.value = 2;,此时 this 指向新创建的对象,新对象拥有了属性 value 且值为 2
      • 接着定义 innerFunc,通过 bind(this) 方法,bind 方法会创建一个新函数,并且将 this 绑定到传入的参数 this(这里就是 AnotherOuter 函数内部的 this,即新创建的对象)。所以当执行 return innerFunc(); 时,this.value 访问的是新创建对象的 value 属性,值为 2。即 result2 的值为 2
  3. 最终输出结果
    • 执行 console.log(result1, result2); 输出 undefined 2

所以代码的输出结果是 undefined 2