MST

星途 面试题库

面试题:JavaScript 中箭头函数与普通函数在 this 指向方面的区别

请阐述 JavaScript 箭头函数与普通函数在 `this` 指向方面有何不同,并通过代码示例说明。
42.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

1. this 指向的不同

  • 普通函数this 的指向在函数被调用时确定,取决于函数的调用方式。如果是作为对象的方法调用,this 指向该对象;如果是独立调用,在非严格模式下,this 指向全局对象(浏览器环境中是 window),在严格模式下,this 指向 undefined
  • 箭头函数:箭头函数没有自己的 this,它的 this 继承自外层作用域(词法作用域),即定义箭头函数的地方的 this

2. 代码示例

// 普通函数
function ordinaryFunction() {
    console.log(this);
}
ordinaryFunction(); // 在非严格模式下,输出全局对象(浏览器中是 window)

const obj = {
    name: 'test',
    method: function() {
        console.log(this);
    }
};
obj.method(); // 输出 obj 对象

// 箭头函数
const arrowFunction = () => {
    console.log(this);
};
arrowFunction(); // 输出全局对象(浏览器中是 window),因为箭头函数继承了外层作用域的 this

const outerObj = {
    name: 'outer',
    inner: {
        name: 'inner',
        arrowMethod: () => {
            console.log(this.name); // 这里输出 'outer',因为箭头函数继承了外层(outerObj 所在作用域)的 this
        }
    }
};
outerObj.inner.arrowMethod();