咸宁兄弟连IT培训学校

173-6295-3551

关于bind

编辑:咸宁兄弟连IT培训学校时间:2019-08-16

下面这段代码会输出什么结果?

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。

1、因为第16行的geet没有在正确的环境下执行。当然,也有很多方法解决这个BUG!

我喜欢使用bind函数来解决问题:

asyncGreet () {

this.someThingAsync()

.then(this.greet.bind(this))

}

这样会确保greet会被Foo的实例调用,而不是局部的函数的this。

2、如果你想要greet永远不会绑定到错误的作用域,你可以在构造函数里面使用bind来绑 。

class Foo {

constructor(name) {

this.name = name this.greet = this.greet.bind(this)

}

}

3、你也可以使用箭头函数(=>)来防止作用域被修改。

asyncGreet() {

this.someThingAsync().then(() = >{

this.greet()

})

}


上一篇:闭包

下一篇:函数声明以及函数表达式

联系方式

选择专业时,如果犹豫不定,不知道选择哪个比较好,敬请致电,专业的咨询老师会为你解答。

  • 报名热线:173-6295-3551
  • 咨询老师:刘老师
  • 点击咨询:

友情连接:

关于我们|联系我们|网站地图

QQ咨询
在线咨询
在线报名
173-6295-3551
返回顶部