面试题答案
一键面试箭头函数的 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指向
在上述代码中:
normalFunction
是普通函数,它的this
指向取决于调用方式,在上述简单调用下,非严格模式指向全局对象,严格模式指向undefined
。arrowFunction
是箭头函数,它的this
指向定义时的外层作用域的this
。- 在
outerFunction
中,通过const self = this
保存外部作用域的this
,然后在innerArrowFunction
中可以访问到外部作用域的this
。通过outerFunction.call({name: 'example'})
改变了outerFunction
的this
指向,innerArrowFunction
也能访问到改变后的this
。