面试题答案
一键面试箭头函数 this
关键字的独特之处
- 不绑定自身
this
:箭头函数没有自己的this
绑定,它的this
取决于其外部(词法)作用域的this
。这与普通函数不同,普通函数在调用时会根据调用的上下文来确定this
。 - 继承外层作用域
this
:箭头函数的this
指向其定义时所处的外层作用域的this
,并且不会被调用方式所改变。
适合使用箭头函数处理 this
关键字的场景
- 回调函数:在使用
setTimeout
、addEventListener
等需要传递回调函数的场景中,如果回调函数中需要访问外层作用域的this
,使用箭头函数可以避免this
指向问题。const obj = { value: 1, start: function() { setTimeout(() => { console.log(this.value); }, 100); } }; obj.start(); // 输出 1,这里箭头函数的 this 继承自 start 函数的 this,也就是 obj
- 数组方法回调:在
map
、filter
、reduce
等数组方法的回调函数中,如果需要访问外层作用域的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
就会因为 this
是 undefined
而报错,但在非严格模式下会返回 undefined
。如果希望 getValue
函数返回 obj
的 value
属性,应该使用普通函数,因为普通函数在作为 obj
的方法调用时,this
会指向 obj
。例如:
const obj = {
value: 1,
getValue: function() {
return this.value;
}
};
console.log(obj.getValue()); // 输出 1