轉(zhuǎn)自http://www.reibang.com/p/ebfeb687eb70
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //undefined says hi
運行上面的代碼會報錯,這是因為setTimeout中的this指向的是全局對象薄榛。所以為了讓它能夠正確的運行,傳統(tǒng)的解決方法有兩種:
1.第一種是將this傳給self,再用self來指代this
says(say){
var self = this;
setTimeout(function(){
console.log(self.type + ' says ' + say)
}, 1000)
2.第二種方法是用bind(this),即
says(say){
setTimeout(function(){
console.log(self.type + ' says ' + say)
}.bind(this), 1000)
- es6中:
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi