coderliush / Blog

博客
0 stars 0 forks source link

es6 之 class #10

Open coderliush opened 3 years ago

coderliush commented 3 years ago

前言

class 概述: **1. class 声明和 class 主体执行环境为严格环境。

  1. class 没有声明提升。** 在 js 中,生成实例对象的传统方法是通过构造函数。比如在 es5 中: image 在 es6 中
coderliush commented 3 years ago

constructor

class 没有 constructor ,默认添加一个空的 constructor,constructor 方法默认返回实例对象(即this)。 function 默认返回 undefined

class Foo {
  constructor() {
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false

Q1: class,function, return 返回值和实例的关系 image

coderliush commented 3 years ago

class 的 this 指向

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>
    );
  }
}
coderliush commented 3 years ago

react class 组件 的 this 指向

在 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>
    );
  }
}