zoukankan      html  css  js  c++  java
  • 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的方法
    豁然开朗!
  • 相关阅读:
    【noip2011】选择客栈
    【noip2013】货车运输
    【bzoj3732】Network
    Codeforces 111C Petya and Spiders (状压dp)
    线段树优化 dijkstra (CF787D Legacy)
    Codeforces 908G Yet Another Maxflow Problem (最小割定理,线段树)
    IOI 2007 Sail (线段树+贪心)
    Codeforces 474E Pillars (树状数组+dp)
    Bzoj 3688 折线统计(dp+树状数组)
    Gorgeous Sequence (线段树)
  • 原文地址:https://www.cnblogs.com/studyhtml5/p/7150576.html
Copyright © 2011-2022 走看看