bind(this)
如果你用过React,或者正在用React作开发,就一定看过或者写过这种代码:
constructor(props){
super(props)
this.handlerEvent = this.handlerEvent.bind(this)
}
handlerEvent(){
//随便写点什么
}
为什么要在这里有一步bind(this)这种操作?它干了点啥?没有bind会怎么样?
其实这三个问题可以一并说:首先,我们先把上面的代码改一下:
class Demo {
constructor(props){
super(props)
}
handlerEvent(){
console.log(this)//Demo
}
}
在不考虑React的前提下,想要调用这个handlerEvent函数那么我们就要
new Demo().handlerEvent(),执行的结果为Demo这个class,这说明调用handlerEvent的是Demo,可是如果把new Demo()赋值给一个变量变成这样:
class Demo {
constructor(props){
super(props)
}
handlerEvent(){
console.log(this)//undefined
}
}
let demo = new Demo().handlerEvent
demo.()
这里的this就变成了undefined(不是指向window是因为使用class会触发严格模式,所以this就成了undefined)。
看到这可能你已经有点明白我说了这么多是啥意思了。
当你在React中绑定时间的时候一定会这样写:
render(){
<button onClick={this.handlerClick.bind(this)}></button>
}
通过上面的例子可以知道,如果把一个函数赋值给一个变量,那么它内部的this就会改变指向,这里把handlerClick赋值给onClick的之前就绑定了内部的this(指向实例本身),所以就不会出现this指向错误的问题
当然解决这个问题的办法不止这一种,你可以在声明这个函数的时候就进行bind,也可以在调用处的外层包裹一层箭头函数,也可以在实例化class的时候(在constructor函数中)将经过绑定的函数赋值给当前函数,方法如下:
class Demo extends Component{
//方法1
constructor(){
this.fn = this.fn.bind(this)
}
//方法2
fn(){
console.log(this)
}.bind(this)
}
arrow(){
console.log(this)
}
//方法3
render(){
return <button onClick={()=>{this.arrow}}>按钮</button>
}
}