MST

星途 面试题库

面试题:TypeScript箭头函数与this指向问题

在TypeScript中,解释箭头函数的this指向规则,并编写一段代码示例,展示箭头函数与普通函数在this指向方面的差异,以及如何在箭头函数中访问外部作用域的this。
16.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

箭头函数的 this 指向规则

箭头函数没有自己的 this,它的 this 继承自外层作用域(词法作用域),即定义箭头函数的地方的 this。它不会根据调用方式改变 this 的指向,始终保持定义时的 this 指向。

代码示例

// 普通函数
function normalFunction() {
    console.log(this); // 在非严格模式下,这里的this指向全局对象(浏览器中是window),在严格模式下是undefined
}

// 箭头函数
const arrowFunction = () => {
    console.log(this); // 这里的this指向定义箭头函数时的外层作用域的this
};

// 调用普通函数
normalFunction();

// 调用箭头函数
arrowFunction();

// 展示如何在箭头函数中访问外部作用域的this
function outerFunction() {
    const self = this; // 保存外部作用域的this
    const innerArrowFunction = () => {
        console.log(self); // 访问外部作用域的this
    };
    innerArrowFunction();
}

// 调用包含箭头函数的外部函数
outerFunction.call({name: 'example'}); // 通过call改变outerFunction的this指向

在上述代码中:

  1. normalFunction 是普通函数,它的 this 指向取决于调用方式,在上述简单调用下,非严格模式指向全局对象,严格模式指向 undefined
  2. arrowFunction 是箭头函数,它的 this 指向定义时的外层作用域的 this
  3. outerFunction 中,通过 const self = this 保存外部作用域的 this,然后在 innerArrowFunction 中可以访问到外部作用域的 this。通过 outerFunction.call({name: 'example'}) 改变了 outerFunctionthis 指向,innerArrowFunction 也能访问到改变后的 this