转自http://www.jianshu.com/p/ebfeb687eb70
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13class 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指向的是全局对象。所以为了让它能够正确的运行,传统的解决方法有两种:
1.第一种是将this传给self,再用self来指代this
复制代码
1
2
3
4
5
6says(say){ var self = this; setTimeout(function(){ console.log(self.type + ' says ' + say) }, 1000)
2.第二种方法是用bind(this),即
复制代码
1
2
3
4
5says(say){ setTimeout(function(){ console.log(self.type + ' says ' + say) }.bind(this), 1000)
- es6中:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13class 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
最后
以上就是机灵小猫咪最近收集整理的关于js-function中this的转换的全部内容,更多相关js-function中this内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复