继承

125 阅读1分钟
function Animal1(name) {
    this.name = name;
}

class Animal2 {
    constructor(name) {
        this.name = name;
    }
}

var a1 = new Animal1('chusheng1');

var a2 = new Animal2('chusheng2');


// 构造函数
function Parent1(name) {
    this.name = name;
}

Parent1.prototype.say = function() {
    console.log('say say say');
}

function Child1(name) {
    Parent1.call(this, name)
}

var p1 = new Parent1('p1');

var c1 = new Child1('c1');

// 原型链继承
function Parent2() {
    this.name = 'p2';
    this.sex = 'm';
    this.arr = [1, 2, 3];
}

function Child2() {
    this.name = 'c2';
}

Child2.prototype = new Parent2();

var c2 = new Child2();

// 注意 引用类型不同,导致继承结果不同
c2.sex = 'f';

c2.arr.push(6);

var c3 = new Child2();

// 组合继承 1
function Parent3() {
    this.name = 4;
    this.arr = [1, 2, 3];
}

function Child3() {
    Parent3.call(this);
    this.type = 's';
}

Child3.prototype = new Parent3();

var c4 = new Child3();
var c5 = new Child3();

// 组合继承 2 减少了一次构造
function Parent4() {
    this.name = 4;
    this.arr = [1, 2, 3];
}

function Child4() {
    Parent4.call(this);
    this.type = 's';
}

Child4.prototype = Parent4.prototype;

var c6 = new Child4();
var c7 = new Child4();

// class 继承
class Parent5 {
    constructor() {
        this.name = 5;
        this.arr = [1, 2, 3];
    }
}

class Child5 extends Parent5 {
    constructor() {
        super();
        this.type = 'm'
    }
}


// 组合寄生继承
function Parent6() {
    this.name = 4;
    this.arr = [1, 2, 3];
}

function Child6() {
    Parent6.call(this);
    this.type = 's';
}

Child6.prototype = Object.create(Parent6.prototype);
Child6.prototype.constructor = Child6;

var d6 = new Child6();
var d7 = new Child6();