MST

星途 面试题库

面试题:JavaScript中this关键字在普通函数和箭头函数中的区别

请详细阐述JavaScript中this关键字在普通函数和箭头函数中的绑定规则有何不同,并通过代码示例说明。
19.6万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

普通函数中this的绑定规则

  1. 默认绑定:在非严格模式下,当函数独立调用(非对象方法调用)时,this 指向全局对象(浏览器中是 window,Node.js 中是 global)。在严格模式下,独立调用函数时,thisundefined
function defaultBinding() {
    return this;
}
// 非严格模式下
console.log(defaultBinding() === window); // true
// 严格模式下
function strictDefaultBinding() {
    'use strict';
    return this;
}
console.log(strictDefaultBinding() === undefined); // true
  1. 隐式绑定:当函数作为对象的方法被调用时,this 指向调用该方法的对象。
const obj = {
    name: 'test',
    getThis: function() {
        return this;
    }
};
console.log(obj.getThis() === obj); // true
  1. 显式绑定:通过 callapplybind 方法可以显式地指定函数中 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
  1. new 绑定:当使用 new 关键字调用函数时,会创建一个新的对象,this 指向这个新创建的对象。
function NewBinding() {
    this.value = 'new binding';
}
const newInstance = new NewBinding();
console.log(newInstance.value); // 'new binding'

箭头函数中this的绑定规则

箭头函数没有自己的 this,它的 this 是在定义时从其外层作用域继承而来的,且不会被 callapplybindnew 改变。

const outerObj = {
    name: 'outer',
    inner: function() {
        const arrowFunc = () => this;
        return arrowFunc();
    }
};
console.log(outerObj.inner() === outerObj); // true

在上述代码中,箭头函数 arrowFuncthis 继承自其外层函数 innerthis,而 inner 作为 outerObj 的方法,其 this 指向 outerObj。所以箭头函数 arrowFuncthis 也指向 outerObj