替代方法: 用 bind:
Greeters.push(console.log.bind(null, i))
还有很多其他方法。这只是我的两个首选
你认为这个会输出什么?
class Foo { constructor (name) {this.name = name } greet () {console.log('hello, this is ', this.name) } someThingAsync () {return Promise.resolve() } asyncGreet () {this.someThingAsync() .then(this.greet) } }new Foo('dog').asyncGreet()
如果你认为这个程序会崩溃提示 Cannot read property 'name' of undefined
,给你一分。
原因: greet
没有在正确的上下文中运行。同样,这个问题依然有很多解决方案。
我个人喜欢
asyncGreet () {this.someThingAsync() .then(this.greet.bind(this)) }
这样可以确保类的实例作为上下文调用greet
。
如果你认为greet
不应该在实例上下文之外运行, 你可以在类的constructor中绑定它:
class Foo {constructor (name) {this.name = namethis.greet = this.greet.bind(this) } }
你还应该知道箭头函数( =>
)可以用来保留上下文。这个方法也可以:
asyncGreet () {this.someThingAsync() .then(() => {this.greet() }) }
尽管我认为最后一种方法并不优雅。
我很高兴我们解决了这个问题。
祝贺你,你现在可以放心地把你的程序放在互联网上了。甚至运行起来可能都不会出岔子(但是通常会)Cheers \o/
如果还有什么我应该提到的,请告诉我!