之前学习Js的时候以为this的指向已经掌握了,没想到在学习React的时候又被this绕晕了,记录一下。🤯
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
//this.tick = this.tick.bind(this);
}
tick () {
this.setState({ date: new Date() });
}
componentDidMount() {
this.timeID = setInterval(() => this.tick(), 1000);
} //挂载
componentWillUnmount() {
clearInterval(this.timeID)
} //卸载
render() {
return (
<div>
<h1>now time is</h1>
<h1>{this.state.date.toLocaleTimeString()}</h1>
</div>
);
}
}
上面是React官方文档的一个计时器demo,一共出现了六次this。
constructor(props) {
super(props);
this.state = { date: new Date() };
constructor中的this,constructor是一种用于创建和初始化clock类创建的对象实例的特殊方法,super是调用父类构造函数,参数就是传到父类构造函数的参数,super(x)即Parent.call(this,x),this指向clock类的实例对象。
tick () {
this.setState({ date: new Date() });
类中的方法tick,同样,指向类的实例化对象。
其实后面的没必要讲了,因为this的指向无非下面几种:
- 当
this定义在一个普通对象的方法中,它指向该对象另外,当类中的方法要引用类属性时,要加上this,否则会报错。 - 当
this定于在一个构造函数/类的方法中,它指向该构造函数/类的实例对象。 - 出现
call,apply,bind方法时,this指向传入的参数对象。
永远的一句话总结,this的指向被调用时所在的上下文。
另外,箭头函数的this绑定在定义时所在的普通函数,不会随着环境的改变而改变,除非那个普通函数的this改变。
