MST

星途 面试题库

面试题:JavaScript箭头函数中this关键字的特性及应用场景

箭头函数的this关键字有什么独特之处?请举例说明在哪些场景下使用箭头函数来处理this关键字会更合适,以及为什么。另外,分析以下代码执行结果,并解释原因。 const obj = { value: 1, getValue: () => { return this.value; } }; console.log(obj.getValue());
42.5万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

箭头函数 this 关键字的独特之处

  1. 不绑定自身 this:箭头函数没有自己的 this 绑定,它的 this 取决于其外部(词法)作用域的 this。这与普通函数不同,普通函数在调用时会根据调用的上下文来确定 this
  2. 继承外层作用域 this:箭头函数的 this 指向其定义时所处的外层作用域的 this,并且不会被调用方式所改变。

适合使用箭头函数处理 this 关键字的场景

  1. 回调函数:在使用 setTimeoutaddEventListener 等需要传递回调函数的场景中,如果回调函数中需要访问外层作用域的 this,使用箭头函数可以避免 this 指向问题。
    const obj = {
        value: 1,
        start: function() {
            setTimeout(() => {
                console.log(this.value);
            }, 100);
        }
    };
    obj.start(); // 输出 1,这里箭头函数的 this 继承自 start 函数的 this,也就是 obj
    
  2. 数组方法回调:在 mapfilterreduce 等数组方法的回调函数中,如果需要访问外层作用域的 this,箭头函数很合适。
    const obj = {
        numbers: [1, 2, 3],
        multiplyByThisValue: function() {
            return this.numbers.map((num) => num * this.value);
        },
        value: 2
    };
    console.log(obj.multiplyByThisValue()); // 输出 [2, 4, 6],箭头函数的 this 指向 obj
    

给定代码的执行结果及原因分析

对于代码:

const obj = {
    value: 1,
    getValue: () => {
        return this.value;
    }
};
console.log(obj.getValue());

执行结果:undefined

原因:箭头函数 getValue 没有自己的 this 绑定,它的 this 取决于其定义时的外层作用域。在这里,箭头函数定义在全局作用域,全局作用域中的 this 在严格模式下是 undefined,在非严格模式下是 window 对象(在浏览器环境)。由于 window 对象上没有 value 属性,所以返回 undefined。如果这是在严格模式下,直接访问 this.value 就会因为 thisundefined 而报错,但在非严格模式下会返回 undefined。如果希望 getValue 函数返回 objvalue 属性,应该使用普通函数,因为普通函数在作为 obj 的方法调用时,this 会指向 obj。例如:

const obj = {
    value: 1,
    getValue: function() {
        return this.value;
    }
};
console.log(obj.getValue()); // 输出 1