MST
星途 面试题库

面试题:JavaScript箭头函数中this与闭包的关系

假设有一个复杂的嵌套函数结构,其中包含箭头函数和普通函数,在这种情况下,this的指向是如何确定的,箭头函数中的this与闭包概念之间存在怎样的联系,请结合实际代码分析。
36.3万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

1. this指向的确定

  • 普通函数
    • 在全局作用域中调用普通函数,this指向全局对象(在浏览器中是window,在Node.js中是global)。例如:
function globalFunc() {
    console.log(this);
}
globalFunc(); 
// 在浏览器环境下输出window对象
- 作为对象方法调用时,`this`指向调用该方法的对象。例如:
const obj = {
    name: 'example',
    printThis: function() {
        console.log(this);
    }
};
obj.printThis(); 
// 输出obj对象
- 使用`call`、`apply`或`bind`方法调用普通函数时,`this`指向传入的第一个参数。例如:
function func() {
    console.log(this.name);
}
const person1 = { name: 'Alice' };
const person2 = { name: 'Bob' };
func.call(person1); 
// 输出'Alice'
func.apply(person2); 
// 输出'Bob'
const newFunc = func.bind(person1);
newFunc(); 
// 输出'Alice'
  • 箭头函数:箭头函数本身没有自己的this,它的this继承自外层作用域(词法作用域)。例如:
const outer = {
    name: 'outerObj',
    inner: function() {
        const arrowFunc = () => {
            console.log(this.name);
        };
        arrowFunc();
    }
};
outer.inner(); 
// 输出'outerObj',这里箭头函数的this继承自outer.inner函数的this

2. 箭头函数中的this与闭包的联系

  • 闭包:闭包是指有权访问另一个函数作用域中的变量的函数。例如:
function outerFunction() {
    let outerVar = 'outerValue';
    function innerFunction() {
        console.log(outerVar);
    }
    return innerFunction;
}
const closure = outerFunction();
closure(); 
// 输出'outerValue',innerFunction形成了闭包,能访问outerFunction作用域中的outerVar
  • 箭头函数与闭包结合:箭头函数由于其this继承自外层作用域,当与闭包结合时,会保持与外层作用域相同的this指向。例如:
const obj = {
    name: 'objName',
    getFunction: function() {
        let localVar = 'localValue';
        return () => {
            console.log(this.name + ' - ' + localVar);
        };
    }
};
const arrowFunc = obj.getFunction();
arrowFunc(); 
// 输出'objName - localValue',箭头函数形成闭包,能访问getFunction作用域中的localVar,同时其this继承自getFunction的this

这里箭头函数不仅形成了闭包可以访问外层函数的局部变量localVar,而且其this指向与外层getFunction函数的this指向一致,都是obj对象。