首页 > 技术文章 > JS继承的几种方式

zhoujingye 2020-05-09 10:37 原文

1. 原型链继承

缺点:引用类型的属性被所有实例共享,在创建Child的实例时,不能向Person传参

function Person(){
    this.name = 'xiaopao';
}

Person.prototype.getName = function(){
    console.log(this.name);
}

function Child(){
}

Child.prototype = new Person();
var child1 = new Child();
child1.getName();  //输出xiaopao

 

2.借用构造函数继承(经典继承)

优点:避免了引用类型的属性被所有实例共享,可以在Child中向Parent传参

缺点:不能继承原型属性,方法都在构造函数中定义,每次创建实例都会创建一遍方法,无法实现函数复用

function Person(){
    this.name = 'xiaopao';
    this.color = ['red','blue','green'];
}

Person.prototype.getName = function(){
    console.log(this.name);
}

function Child(){
    Person.call(this);  //使用call方法继承父类构造函数中的属性
}

var child1 = new Child();
var child2 = new Child();
child1.colors.push(‘yellow’);
console.log(child1.name)
console.log(child1.colors); //[red,blue,green,yellow]
console.log(child2.colors);//[red,blue,green]

借用构造函数继承,如何向Parent传参

function Person(name){
    this.name = name;
}

Person.prototype.getName = function(){
    console.log(this.name)
}

function Child(name){
    Person.call(this,name);
}

var child1 = new Child('xiaopao')
var child2 = new Child('lulu')

console.log(child1.name) //xiaopao
console.log(child2.name) //lulu

console.log(child1 instanceof Person)  //false,不能识别是Person的实例,只是Child子类的实例

 

3. 组合继承,结合原型链继承和构造函数继承,使用原型链实现原型方法的继承,使用构造函数实现属性的继承

优点:融合原型链继承和构造函数继承的有点,是JS中最常用的继承模式

缺点:调用了两次父类构造函数

function Parent(name){
    this.name = name;
    this.colors = ['red','blue','green'];
}

Parent.prototype.getName = function(){
    console.log(this.name);
}

function Child(name,age){
    Parent.call(this,name);  //第二次调用Parent() 构造函数方法 继承属性
    this.age = age ; //添加自己的属性
}

Child.prototype = new Parent(); //第一次调用Parent()  原型链方法 继承原型方法
(这一步相当于:Child.prototype.__proto__ = Parent.prototype)
var child1 = new Child('xiaopao',18) var child2 = new Child('lulu',19) child1.getName() //xiaopao child2.getName() //lulu console.log(child1.age); // 18 console.log(child2.age); // 19 child1.colors.push('yellow'); console.log(child1.colors); // ["red", "blue", "green", "yellow"] console.log(child2.colors); // ["red", "blue", "green"] console.log(child1 instanceof Child) //true console.log(child1 instanceof Parent) //true

 

4.原型式继承

5.寄生虫式继承

6.寄生组合式继承

7.ES6 使用class类 extends super继承

class Animal{
    constructor(color) { this.color = color }
    move(){}
}

class Dog extends Animal{
    constructor(color,name){
        super(color)   //继承父类属性
        this.name = name  //创建自己属性
    }
    move(){
        super.move(); //继承父类方法
    }
    say(){}; //创建自己方法
}

 

资料参考: https://www.jianshu.com/p/85899e287694

推荐阅读