MST

星途 面试题库

面试题:JavaScript 中复杂嵌套函数的 this 绑定分析及解决方法

分析以下代码中 this 的指向,并解释原因。如果要使内部函数中 this 指向外部函数的 this,应该如何修改代码?请至少提供两种方法。 ```javascript function outerFunction() { this.value = 10; function innerFunction() { console.log(this.value); } innerFunction(); } outerFunction(); ```
11.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 分析 this 指向
    • outerFunction 中,this 指向全局对象(在浏览器环境下是 window,在 Node.js 环境下是 global),因为 outerFunction 是作为一个普通函数调用的,非严格模式下普通函数调用时 this 指向全局对象。
    • innerFunction 中,this 同样指向全局对象(在非严格模式下)。因为 innerFunction 也是普通函数调用,在非严格模式下普通函数调用时 this 指向全局对象。这里 console.log(this.value) 实际访问的是全局对象的 value 属性,而不是 outerFunction 中的 this.value
  2. 修改代码使内部函数中 this 指向外部函数的 this 的方法
    • 方法一:使用 var that = this
function outerFunction() {
    this.value = 10;
    var that = this;
    function innerFunction() {
        console.log(that.value);
    }
    innerFunction();
}
outerFunction();

这里在 outerFunction 内部声明一个变量 that 并赋值为 this,这样在 innerFunction 中通过 that 就能访问到 outerFunction 中的 this 所指向对象的属性。

  • 方法二:使用 Function.prototype.bind
function outerFunction() {
    this.value = 10;
    function innerFunction() {
        console.log(this.value);
    }
    var boundInnerFunction = innerFunction.bind(this);
    boundInnerFunction();
}
outerFunction();

bind 方法创建一个新的函数,在调用新函数时,this 会被绑定到 bind 方法传入的第一个参数。这里将 innerFunctionthis 绑定到 outerFunction 中的 this,从而实现内部函数访问外部函数 this 的属性。

  • 方法三:使用箭头函数
function outerFunction() {
    this.value = 10;
    const innerFunction = () => {
        console.log(this.value);
    };
    innerFunction();
}
outerFunction();

箭头函数没有自己的 this,它的 this 继承自外层作用域的 this。这里外层作用域是 outerFunction,所以箭头函数 innerFunction 中的 this 指向 outerFunction 中的 this,能够正确访问 this.value