1. 原型链继承
function Brother(name){
this.name = name;
this.wives = ["奶茶"];
this.marry = function(){};
}
function Employee(name) {
this.name = name;
}
Employee.prototype = new Brother();
优点:书写简单
缺点: 无法给父类构造函数传参,子类会继承父类的所有引用类型,一旦原地修改就会影响所有子类。
const brother = new Brother("刘强东");
const employee1 = new Employee("刘强东的兄弟");
const employee2 = new Employee("刘强东的兄弟2");
console.log(employee1.wives); // 奶茶
console.log(employee2.wives); // 奶茶
employee1.wives.push("绿茶");
console.log(employee1.wives); // 奶茶,绿茶
console.log(employee2.wives); // 奶茶,绿茶
employee1.wives = ["绿茶"]; // 指向不同对象
console.log(employee1.wives); // 绿茶
console.log(employee2.wives); // 奶茶,绿茶
2.借用构造函数
function Brother(name){
this.name = name;
this.wives = ["奶茶"];
this.marry = function(){};
}
function Employee(name, age) {
Brother.call(this, name);
this.age = age;
}
缺点:父类方法内的函数每次都会生成新的拷贝;通过prototype定义的方法无法继承
3. 组合继承 (原型链 + 借用构造函数)
function Brother(name){
this.name = name;
this.wives = ["奶茶"];
}
Brother.prototype.marry = function() {}
function Employee(name, age) {
Brother.call(this, name);
this.age = age;
}
Employee.prototype = new Brother();
缺点: 多次调用构造函数
4.原型式继承 duck type 鸭式辨型
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
或者直接object.create(o);
使用场合:没必要构建构造函数,仅仅是想模拟一个对象的时候
缺点:同原型链
5.寄生继承
function(original){
newObj = Object(original)
newObj.newFunc =(){}
return newObj
}
缺点:方法在函数中定义,无法得到复用
6.寄生组合
function inheritPrototype(subType, supType) {
var p = Object(supType.prototype);
p.constructor = subType;
subType.prototype = p;
}
function subType(){
supType.call(this);
}
inheritProptype(subType, supType)