首页 > 解决方案 > 从另一个函数调用的箭头函数中“this”的值

问题描述

我有两个对象

var dog1 = {
    sound: "bark1!",
    bark: () => {
        console.log(this)
        console.log(this.sound);
    }
}

var dog2 = {
    sound: "bark2!",
    bark: function() {
        console.log(this);
        console.log(this.sound);
        dog1.bark();
    }
}

现在我知道,如果我调用,dog1.bark()我的值this将等于Windowobject,因为this箭头函数的值取决于词法范围。

但是,如果我调用dog2.bark()并在调用时从其中dog1.bark()调用,那么值不应该this是 dog2 吗?既然箭头函数的词法范围是 dog2 的 bark 函数?或者我在这里错过了什么?

希望对此进行一些澄清。我注意到这个问题被标记为重复,我不明白为什么从旧式函数调用对象仍然导致值this等于window

标签: javascriptecmascript-6this

解决方案


推荐阅读