ES6 笔记 之 class, extends, super

class, extends, super 这三个特性涉及了ES5中最令人头疼的的几个部分:原型、构造函数,继承 ,由于博主是写react 的所以经常看到,但是刚开始的时候不太了解其中的工作原理

例如

class Animal {
 constructor(){
  this.type = 'animal'
 }
 says(say){
  console.log(this.type + ' says ' + say)
 }
}

let animal = new Animal()
animal.says('hello') //animal says hello

class Cat extends Animal {
 constructor(){
  super()
  this.type = 'cat'
 }
}

let cat = new Cat()
cat.says('hello') //cat says hello

首先用class定义了一个“类”,可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象。简单地说,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的。

Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。上面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。

super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

下面来看一段我日常写的 react+ES6 代码

import React from 'react';
export class Master extends React.Component<any,any> {

constructor(props) {
super(props);
this.state = {
loading:false
};
}
 componentDidMount(){
  
 }
 render(){
  return (
    <div>Master</div>
  )
 }
}
那么现在就应该能理解ES6+react的组件化思想实现的原理了,定义一个继承React.Component的Master的类,构造方法constructor()里定义this.state私有属性,而constructor 外的componentDidMou
nt和render方法是继承到的React.Component的方法
豁然开朗!
原文地址:https://www.cnblogs.com/studyhtml5/p/7150576.html