Javascript 组合继承 原型链继承 寄生继承

时间:2021-09-22 20:03:23

Javascript继承通常有三种方式。

第一种:组合式继承:

    function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
//通过call()调用SuperType的构造函数,继承SuperType属性
SuperType.call(this, name); //第二次调用 SuperType()
this.age = age;
}
SubType.prototype = new SuperType(); //第一次调用
SubType.prototype.sayAge = function() {
console.log(this.age);
};
var instancel = new SubType("Nicholas", );
SuperType()

该继承通过构造函数继承原型链的方法和父类的属性,但该方法会有两次调用父类,第一次是在继承原型链,第二次在继承属性。

第二种:原型链继承

//原型式继承实例代码:
function createObj(o) {//对传入的对象执行了一次浅复制
function F() {}
F.prototype = o;
return new F();
}
var person = {
name: "Tom",
friends: ["one", "two", "van"]
};
var huPs = createObj(person);
huPs.name = "GRE";
huPs.friends.push("Rob"); var yePs = createObj(person);
yePs.name = "Lin";
yePs.friends.push("Sari"); console.log(person.friends);//"one,two,van,Rob,Sari"

这个没什么,Js的原型继承特性。

第三种:寄生式继承

在第一种的方法上,我们在第一次调用父类,也就是继承原型的时候,实际上只需要父类的原型副本,那么取得副本,也就省去了这一次调用。

该继承技术是最常用的。

function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype); //创建对象 超类型原型副本
prototype.constructor = subType; //增强对象 为副本增添construct属性
subType.prototype = prototype; //指定对象
}
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
console.log(this.name);
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
console.log(this.age);
};

 该文章参考自https://my.oschina.net/quidditch/blog/307551