ES6与ES5继承比较

来源:互联网 发布:经传软件试用版 编辑:程序博客网 时间:2024/04/29 14:55

1. 关于ES5寄生构造函数继承

    /*寄生组合式继承*/function inHeritPrototype(SuperType,SubType) {    var prototype=Object(SuperType);//创建对象    prototype.constructor=SubType;//增强对象    SubType.prototype=prototype;}function SuperType(name){    this.name=name;    this.colors=["blue","white"];}SuperType.prototype.sayName=function () {    console.log(this.name);};function SubType(age,name) {    SuperType.call(this, name);    this.age=age;}inHeritPrototype(SuperType,SubType);SubType.prototype.sayAge=function () {    return this.age;};var instance1=new SubType("hello",28);console.log(instance1);

2. ES6继承方法

 class SuperType{        constructor(name){            this.name=name;            this.colors=["blue","white"]        }        sayName(){            console.log(this.name)        }    }    class SubType extends SuperType{        constructor(name,age){            super(name);//super调用父类的方法,会绑定子类的this.            this.age = age;        }        sayAge(){            return this.age;        }    }    var instance2 = new SubType("hello",29);    console.log(instance2);

ES5继承实质:先创建实例对象this,再将父类方法添加到this上面。
ES6继承实质:先创造父类的实例对象this,用子类的构造函数修改this.

原创粉丝点击