箭头函数中的this永远指向全局对象? 不是!!!!!!

箭头函数并没有自己的this值,它捕获定义时所在上下文的this值作为自己的this值。

也就是说,箭头函数中的 this是在定义时绑定的,而不是在调用时绑定

在全局上下文中定义的箭头函数,其this值会指向全局对象(在浏览器中是window对象)。

(1)、箭头函数中的this指向某个对象

如果在某个对象的方法内部 定义箭头函数,那么这个箭头函数的this值就会绑定到其所在的对象;

例如:

let obj = {
    value: "obj",
    method: function () {
        let arrowFunction = () => {
            console.log(this.value); // 输出 "obj",因为arrowFunction的this绑定到了obj的this
        }
        arrowFunction();
    }
}
obj.method(); // 输出 "obj"

在上面的例子中,无论是在outerFunction还是在obj.method中定义的箭头函数,它们的this都绑定到了它们所在上下文的this值,而不是全局对象。

(2)、箭头函数中的this指向某个对象

如果在某个函数内部 定义箭头函数,那么这个箭头函数的this值就会绑定到外部函数的this值。

⚠️ 外部函数的this是调用时绑定的,这意味着内部定义的箭头函数this也会跟着发生变化。

function outerFunction() {
    this.name = "outerFunction";
    let arrowFunction = () => {
        console.log(this);
    }
    arrowFunction();
}
outerFunction(); // 箭头函数输出的是 window 对象
// Window {window: Window, self: Window, document: document, name: 'outerFunction', location: Location, …}

let obj = {};
obj.f = outerFunction;
obj.f();// 箭头函数输出的是 obj 对象
// {name: 'outerFunction', f: ƒ}