我有两个对象声明。一种是不使用类,第二种是通过类创建的。我知道我必须在第一个的print方法中使用bind()来引用对象数组,因为setTimeout方法是指向window的,因此我需要更改“ this”关键字的上下文。我的问题是为什么在第二个中我不使用bind()并且结果完全相同?
let obj = {
time: 2000,
array: ["cat", "dog", "tortoise", "bat"],
print: function(){
setTimeout(function(){
this.array.forEach(el => console.log(el.toUpperCase()));
}.bind(this), this.time);
}
}
obj.print();
class Obj {
constructor(){
this.time = 2000;
this.array = ["cat", "dog", "tortoise", "bat"];
}
print(){
setTimeout(()=>{
this.array.forEach(el => console.log(el.toUpperCase()));
}, this.time);
}
}
let o = new Obj();
o.print();
答案 0 :(得分:1)
因为在第二个(类)对象中,您使用了一个===========================
TYPE_VEH D1 D2
===========================
CAR 2 8
BUS 2 2
函数,该函数将===========================
TYPE_VEH D1 D2
===========================
CAR 20% 80%
BUS 50% 50%
绑定到它的词法作用域(类arrow
),而不是传统的函数将this
绑定到调用位置(从中调用函数)。