Open coderliush opened 3 years ago
class 没有 constructor ,默认添加一个空的 constructor,constructor 方法默认返回实例对象(即this)。 function 默认返回 undefined
class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo
// false
Q1: class,function, return 返回值和实例的关系
class 最后都被 new 调用,所以 class 的 this 都指向实例 ,(参见 new )。 在 react 中,类继承了 react,所以实例可以从原型链上获得 react 的方法。所以常见的做法,在 constructor 中的函数绑定 this,this 指向 instance 。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.handleClick = this.handleClick.bind(this); // this 指向 Toggle 的实例
}
// 不绑定的时候,事件里的 this 指向 window
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={ this.handleClick }> // this 指向 类的实例。handleClick 在实例的原型链上,所以可以找到。
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
在 react 中,类继承了 react,所以实例可以从原型链上获得 react 的方法。所以常见的做法,在 constructor 中的函数绑定 this,this 指向 instance 。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
this.handleClick = this.handleClick.bind(this); // this 指向 Toggle 的实例
}
// 不绑定的时候,事件里的 this 指向 window
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={ this.handleClick }>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
前言
class 概述: **1. class 声明和 class 主体执行环境为严格环境。