javascript中的继承方式及其特点(extend)

js中的继承:子类共享父类的属性和方法,js的继承都是基于原型实现的。

js继承分为以下几种继承:

首先咱们先定义一个动物类`

function Animal (name) {
    // 属性
    this.name = name;
    // 实例方法
    this.say= function(){
      console.log("My name is "+this.name);
    }
}
// 原型方法
Animal.prototype.eat = function(food) {
    console.log(this.name + '正在吃:' + food);
};

1、原型链继承:子类的原型指向父类的实例

function Cat(){
}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';


var cat = new Cat();
console.log(cat.name);
cat.say();
cat.eat('fish');
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
原型链继承的特点
  1.非常纯粹的继承关系,实例是子类的实例,也是父类的实例
  2.父类新增原型方法/原型属性,子类都能访问到
  3.简单,易于实现
原型链继承的缺点
1.要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
2.无法实现多继承
3.来自原型对象的引用属性是所有实例共享的
4.创建子类实例时,无法向构造函数传参

2、构造继承(call、apply继承)

function Cat(name){
    Animal.call(this,name);
}

var cat = new Cat("Tom");
console.log(cat.name);
cat.say();
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
构造继承特点:

1、解决了1中,子类实例共享父类引用属性的问题
2、创建子类实例时,可以向父类传递参数
3、可以实现多继承(call多个父类对象)

构造继承缺点:

1、实例并不是父类的实例,只是子类的实例
2、只能继承父类的实例属性和方法,不能继承原型属性/方法
3、无法实现函数复用,每个子类都有父类实例函数的副本,影响性能

3、拷贝继承

function Cat(name){
    var animal = new Animal(name);
    for(var key in animal){
        Cat.prototype[key] = animal[key];
    }
}
// Test Code
var cat = new Cat("Tom");
console.log(cat.name);
cat.say();
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
拷贝继承特点:
1、支持多继承
拷贝继承缺点:
1、效率较低,内存占用高(因为要拷贝父类的属性)
2、无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到)

4、组合继承(原型链和构造继承的组合)

function Cat(name){
    Animal.call(this,name);
}

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

// Test Code
var cat = new Cat();
console.log(cat.name);
cat.say();
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
组合继承特点

1、弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法
2、既是子类的实例,也是父类的实例
3、不存在引用属性共享问题
可传参
4、函数可复用

组合继承缺点:
1、调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)

5、寄生组合继承

function Cat(name){
    Animal.call(this);
    this.name = name;
}
(function(){
    // 创建一个没有实例方法的类
    var Super = function(){};
    Super.prototype = Animal.prototype;
    //将实例作为子类的原型
    Cat.prototype = new Super();
})();

// Test Code
var cat = new Cat();
console.log(cat.name);
cat.say();
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

寄生组合继承特点:堪称完美
寄生组合继承缺点:实现较为复杂

6、 ES6继承(语法糖)

class Animal{
    constructor(name){
        this.name = name;
    }
    say(){
        alert("My name is "+this.name);
    }
    eat(food){
        alert(this.name+" is eating "+food);
    }
}
class Cat extends Animal{
    constructor(name){
        super(name);
    }
}

var  tom = new Cat("Tom");
tom.say();
tom.eat("apple");
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

ES6继承特点:用得最舒服

发布了1 篇原创文章 · 获赞 0 · 访问量 16

猜你喜欢

转载自blog.csdn.net/qq_42259050/article/details/104464793