ECMAScript6 (4) 类

类的声明

ECMAScript6中有一种与其他语言中类似的类特性: 类声明

同时它也是ECMAScript6中最简单的类形式

要声明一个类

class Student{
    constructor(name){
        this.name = name;
    }
    sayName(){
        console.log(this.name);
    }
}

new Student('Li').sayName();

然后强调一下构造器中的this

其值会被绑定到调用this的函数的最近的父对象

var person = {
  first: 'John',
  last: 'Smith',
  full: function() {
    console.log(this.first + ' ' + this.last);
  },
  personTwo: {
    first: 'Allison',
    last: 'Jones',
    full: function() {
      console.log(this.first + ' ' + this.last);
    }
  }
};

person.full();
//输出 'John Smith'
person.personTwo.full();
//输出 'Allison Jones'

这里React构造函数中经常写的

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
}

bind()方法会创建一个新函数,当这个新函数被调用时,它的this值是传递给bind()的第一个参数, 它的参数是bind()的其他参数和其原本的参数. 

也就是说, this.handleClick.bind(this); 这句代码执行之后会创建一个新函数, 然后把这个函数赋值给等号左边的原函数引用( 当然你也可以起名叫 this.newHandleClick )

rendor函数中的 

<button onClick={this.handleClick}> {this.state.isToggleOn ? ‘ON’ : ‘OFF’} </button>

调用的实际上是新函数, 调用这个新函数的this值也就赋给了bind的参数this, 也就传入了handleClick函数的内部

如果去掉这句绑定, 那么构造函数中的this和handleClick函数中的this就成了不同的this