class Animal {
constructor(){
console.log(this);
this.type = 'animal'
}
says(say){
setTimeout(function(){
console.log(this);
console.log(this.type + ' says ' + say)
}, 1000)
}
}
为什么一个this是Animal对象,一个this是window对象?
这是JS中一个不好的地方:
setTimeout
的执行上下文是window
对象而不是class Animal
. 导致了setTimeout
中的函数是基于全局作用域执行, 其中的this
指向了window
可以这样解决(ES6):