ES6与ES5继承比较

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.

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值