面试题答案
一键面试1. 普通函数的 this
绑定机制
普通函数的 this
指向取决于函数的调用方式:
- 作为对象方法调用:
this
指向调用该方法的对象。 - 独立调用:在非严格模式下,
this
指向全局对象(浏览器中是window
,Node.js 中是global
);在严格模式下,this
是undefined
。 - 通过
call
、apply
、bind
调用:this
指向传入的第一个参数。
示例代码:
const obj = {
name: 'John',
sayHello: function() {
console.log(`Hello, ${this.name}`);
}
};
obj.sayHello(); // Hello, John
function sayHi() {
console.log(`Hi, ${this.name}`);
}
sayHi(); // Hi, undefined(非严格模式下,this 指向全局对象,全局对象没有 name 属性)
const sayHey = sayHi.bind({ name: 'Jane' });
sayHey(); // Hi, Jane
2. 箭头函数的 this
绑定机制
箭头函数没有自己的 this
,它的 this
继承自外层作用域(词法作用域)。也就是说,箭头函数的 this
指向在定义时就已经确定,而不是在调用时确定。
3. 箭头函数处于闭包环境时 this
对闭包的影响
当箭头函数处于闭包环境时,它会捕获并保持外层作用域的 this
。这可能会导致一些与普通函数不同的行为。
示例代码:
function outer() {
this.name = 'Outer';
const innerArrow = () => {
console.log(this.name);
};
return innerArrow;
}
const outerObj = new outer();
const innerFunc = outerObj();
innerFunc(); // Outer
function outerNormal() {
this.name = 'OuterNormal';
function innerNormal() {
console.log(this.name);
}
return innerNormal;
}
const outerNormalObj = new outerNormal();
const innerNormalFunc = outerNormalObj();
innerNormalFunc(); // undefined(在非严格模式下,独立调用时 this 指向全局对象,全局对象没有 name 属性)
4. 原理解释
- 箭头函数:箭头函数的
this
绑定是基于词法作用域的,它会捕获定义时外层作用域的this
。在上述示例中,innerArrow
定义在outer
函数内部,它捕获了outer
函数中的this
,此时this
指向outer
函数的实例outerObj
。 - 普通函数:普通函数的
this
指向在调用时确定。在innerNormal
函数独立调用时,它不是作为某个对象的方法调用,所以在非严格模式下this
指向全局对象,导致输出undefined
。
总结来说,箭头函数在闭包环境中对 this
的捕获和保持,使得它在处理 this
时与普通函数有显著区别,开发者在使用时需要注意这种差异,以避免出现意外的行为。