您的位置:首页 > 其它

ES6与ES5继承比较

2017-07-28 11:36 459 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: