奇怪的this

        var obj = {
            id: "awesome",
            cool: () => {  // 普通函数this是在运行时确定的,而箭头函数绑定了上层函数或window的this
                console.log(this.id);
            }
        };
        var id = "not awesome";
        obj.cool();  // not awesome
        setTimeout(obj.cool, 1000);  // not awesome

obj.cool() 执行调用时,this本应该指向obj,但是因为cool是用箭头函数声明的,所以cool本身绑定了词法作用域,也就是绑定了被声明时上层函数的this,上层函数的this是啥就是啥,如果没有则指向window。

posted @ 2023-04-20 16:16  黄燃  阅读(16)  评论(0)    收藏  举报