16-ES5和ES6创建类的转换

162 阅读1分钟

es5 创建类

function Plane(numEngines) {
  this.numEngines = numEngines;
  this.enginesActive = false;
}

// methods "inherited" by all instances
Plane.prototype.startEngines = function () {
  console.log("starting engines...");
  this.enginesActive = true;
};

const richardsPlane = new Plane(1);
richardsPlane.startEngines();

const jamesPlane = new Plane(4);
jamesPlane.startEngines();

es6 创建类

Class Plane{
    constructor(numEngines){
        this.numEngines = numEngines;
    }
    startEngines(){
    console.log("starting engines...");
    this.enginesActive = true;
    }
}
const richardsPlane = new Plane(1);
richardsPlane.startEngines();

const jamesPlane = new Plane(4);
jamesPlane.startEngines();

es5中的super与extends

function Tree(size,leaves){
    this.size = size || 10;
    this.leaves = leaves || {spring: 'green', summer: 'green', fall: 'orange', winter: null};
    this.leftColor ;
}

Tree.prototype.changeSeason = function(season){
    this.leftColor = this.leaves[season];
    if(season === 'spring'){
        this.size += 1
    }
}

function Map(syrupQty,size,leaves){
    Tree.call(this,size,leaves);
    this.syrupQty = syrupQty || 15;
}
Map.prototype=Object.create(Tree.prototype);
Map.prototype.constructor = Map;

Map.prototype.changeSeason = function(season){
    Tree.prototype.changeSeason.call(this,season);
    if(season === 'spring'){
        this.syrupQty += 1;
    }
}
Map.prototype.gatherSyrup = function(){
    this.syrupQty -=3;
}
const myMap = new Map(15,5);
myMap.changeSeason('fall');
myMap.gatherSyrup();
myMap.changeSeason('spring');

es6中的super与extends

Class Tree{
    constructor(size=10,leaves={spring: 'green', summer: 'green', fall: 'orange', winter: null}){
        this.size = size;
        this.leaves = leaves;
        this.leftColor = null;
    }

    changeSeason(season){
        this.leftColor = this.leaves[season];
        if(season === 'spring'){
            this.size += 1;
        }
    }
}

Class Map extends Tree{
    constructor(syrupQty=15,size,leaves){
        super(size,leaves)//super被当作函数
        this.syrupQty = syrupQty;
    }
    changeSeason(season){
        super.changeSeason(season);//super被当作对象
        if(season === 'spring'){
            this.syrupQty += 1;
        }
    }
    gatherSyrup(){
        this.syrupQty -= 3;
    }
}

对于上面可以这么理解:

  • extends关键字将Map的的prototype指向Tree的prototype,并且将Map上的prototype上的constructor指向自身
  • super可以理解为类Tree,在这里的有两种使用方式,第一种是函数,二种是对象。