JS中的this指向

107 阅读1分钟

概述

普通函数:关于this,谁调用就指向谁没有调用者,就指向全局对象window

箭头函数:箭头函数的this指向于函数作用域所用的对象

具体情况

普通函数

  • 默认绑定:默认绑定是指,当函数独立调用时(即没有调用者),this指向window
function fun() {
    console.log("隐式:", this);
}
fun(); // whindow
  • 隐式绑定:隐式绑定与默认绑定相对应,隐式绑定可以大致理解为谁调用,this就指向谁,即this指向当前执行上下文;
let obj = {
    foo: function () {
        console.log(this);
    }
};
let bar = obj.foo;
bar(); // whindow
obj.foo(); // obj
  • 显式绑定:对象内部方法的this指向调用这些方法的对象也就是谁调用就指向谁
let foo = function () {
    console.log(this);
};
foo.call({ a: "a", b: "b" });
  • new绑定:当使用new来实例化一个构造函数时,this指向实例
class the {
    static a = "a";
    constructor(val) {
        this.val = val;
    }
    fun() {
        console.log(this);
    }
}
new the(1).fun(); // { val: 1 }

箭头函数

箭头函数自身没有this,所以需要沿着作用域链向上进行查找,直到找到this(普通函数或者window)。

let arrow1 = () => {
    console.log("箭头函数arrow1:", this);
};
let obj = {
    a: "a",
    fun: function () {
        let arrow2 = () => {
            console.log("箭头函数arrow2:", this);
        };
        arrow1();
        arrow2();
    }
};
obj.fun();
// whindow
//{"a": "a"}

参考

JavaScript中的this指向总结

JS中的this指向