继承(7种)

95 阅读1分钟
1.原型链式继承

将父类的实例作为子类的原型

function Animal (name) {
    this.name = name;
    this.say = function(){ console.log(I’m this.name); }
 }
 // 原型对象方法
 Animal.prototype.eat = function(food) {
     console.log(this.name + '正在吃:' + food);
 };
 function Cat(){ }
 Cat.prototype = new Animal();
 Cat.prototype.name = 'cat’; 
 var cat = new Cat();
2.构造函数继承
// 定义一个父类型
function Animal (name) {
    this.name = name;
    this.say = function(){ console.log(I’m this.name); }
 }
 // 原型对象方法
Animal.prototype.eat = function(food) {
    console.log(this.name + '吃:' + food);
}; 
function Cat(name,age){
    Animal.call(this,name);
    this.age = age;
} 
var cat = new Cat();
3.实例继承
// 定义一个父类型
function Animal (name) {
    this.name = name; 
    this.say = function(){ console.log(I’m this.name); } 
}
// 原型对象方法
Animal.prototype.eat = function(food) {
    console.log(this.name + '吃:' + food);
};
function Cat(name,age){
    var o = new Animal(name);
    //先创建子类型实例
    o.age = age;
    return o;
} 
var cat = new Cat();
4.拷贝继承

无法获取父类不可for in遍历的方法

// 定义一个父类型
function Animal (name) {
    this.name = name;
    this.say = function(){ console.log(I’m this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {
    console.log(this.name + '吃:' + food);
}; 
function Cat(name,age){
    var animal = new Animal(name);
    for(var p in animal){
        Cat.prototype[p] = animal[p];
    } 
    this.age = age
}
var cat = new Cat();
5.组合继承
// 定义一个父类型
function Animal (name) {
    this.name = name;
    this.say = function(){ console.log(I’m this.name); }
}
// 原型对象方法
Animal.prototype.eat = function(food) {
    console.log(this.name + '吃:' + food);
};
function Cat(name,age){
    Animal.call(this,name);
    this.age = age
} 
Cat.prototype = new Animal(); 
Cat.prototype.constructor = Cat;
var cat = new Cat();
6.寄生组合继承
// 定义一个父类型
function Animal (name) {
    this.name = name;
    this.say = function(){ console.log(I’m this.name); }
}
// 原型对象方法 
Animal.prototype.eat = function(food) {
    console.log(this.name + '吃:' + food);
};
function Cat(name,age){
    Animal.call(this,name);
    this.age = age
} 
(function(){ 
    // 创建一个没有实例方法的类 
    var Super = function(){}; 
    Super.prototype = Animal.prototype; 
    //将实例作为子类的原型 
    Cat.prototype = new Super(); 
})(); 
var cat = new Cat();
7.ES6 class extends继承
Class 父类型{ constructor(){ } … } 
Class 子类型 extends 父类型{ constructor(){ super(); } }