面试题答案
一键面试普通函数中this的绑定规则
- 默认绑定:在非严格模式下,当函数独立调用(非对象方法调用)时,
this
指向全局对象(浏览器中是window
,Node.js 中是global
)。在严格模式下,独立调用函数时,this
是undefined
。
function defaultBinding() {
return this;
}
// 非严格模式下
console.log(defaultBinding() === window); // true
// 严格模式下
function strictDefaultBinding() {
'use strict';
return this;
}
console.log(strictDefaultBinding() === undefined); // true
- 隐式绑定:当函数作为对象的方法被调用时,
this
指向调用该方法的对象。
const obj = {
name: 'test',
getThis: function() {
return this;
}
};
console.log(obj.getThis() === obj); // true
- 显式绑定:通过
call
、apply
、bind
方法可以显式地指定函数中this
的值。
function explicitBinding() {
return this;
}
const newObj = { value: 'new' };
console.log(explicitBinding.call(newObj) === newObj); // true
console.log(explicitBinding.apply(newObj) === newObj); // true
const boundFunc = explicitBinding.bind(newObj);
console.log(boundFunc() === newObj); // true
- new 绑定:当使用
new
关键字调用函数时,会创建一个新的对象,this
指向这个新创建的对象。
function NewBinding() {
this.value = 'new binding';
}
const newInstance = new NewBinding();
console.log(newInstance.value); // 'new binding'
箭头函数中this的绑定规则
箭头函数没有自己的 this
,它的 this
是在定义时从其外层作用域继承而来的,且不会被 call
、apply
、bind
或 new
改变。
const outerObj = {
name: 'outer',
inner: function() {
const arrowFunc = () => this;
return arrowFunc();
}
};
console.log(outerObj.inner() === outerObj); // true
在上述代码中,箭头函数 arrowFunc
的 this
继承自其外层函数 inner
的 this
,而 inner
作为 outerObj
的方法,其 this
指向 outerObj
。所以箭头函数 arrowFunc
的 this
也指向 outerObj
。