面试题答案
一键面试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
对象。