MST

星途 面试题库

面试题:JavaScript 中箭头函数与普通函数在 this 指向方面有何不同

请详细阐述 JavaScript 里箭头函数与普通函数在 this 指向规则上的差异,并举例说明在实际代码场景中如何体现这种差异。
41.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

差异

  1. 普通函数this 的指向在函数被调用时确定,取决于函数的调用方式。
    • 全局作用域中:在非严格模式下,普通函数内部的 this 指向全局对象(浏览器中是 window);在严格模式下,thisundefined
    • 作为对象方法调用this 指向调用该方法的对象。
    • 通过 callapplybind 调用this 指向传入的第一个参数。
  2. 箭头函数this 的指向在定义时确定,取决于外层(函数或全局)作用域的 this。它没有自己的 this 绑定,会捕获其所在上下文的 this 值,作为自己的 this 值。

实际代码场景示例

  1. 普通函数示例
function NormalFunction() {
    console.log(this);
}
// 非严格模式下,在全局作用域调用
NormalFunction(); // 在浏览器中输出 window 对象

const obj = {
    name: 'test',
    normalFunc: function() {
        console.log(this.name);
    }
};
obj.normalFunc(); // 输出 'test',this 指向 obj

function anotherFunc() {
    console.log(this.name);
}
const newObj = { name: 'newTest' };
anotherFunc.call(newObj); // 输出 'newTest',通过 call 改变 this 指向 newObj
  1. 箭头函数示例
const obj2 = {
    name: 'arrowTest',
    arrowFunc: () => {
        console.log(this.name);
    }
};
obj2.arrowFunc(); 
// 这里的 this 指向全局作用域(浏览器中是 window),通常 window 上没有 name 属性,所以输出 undefined

function outer() {
    this.name = 'outerTest';
    return () => {
        console.log(this.name);
    };
}
const arrow = outer.call({name: 'callTest'});
arrow(); 
// 这里箭头函数的 this 指向 outer 函数调用时的 this,即 {name: 'callTest'},输出 'callTest'