Js中的几种继承方式?

2020-05-11  本文已影响0人  风雅欢乐

直接从代码中看

// 1. 借助构造函数实现继承
function Parent1() {
    this.name = 'parent1';
}
Parent1.prototype.say = function () {
    console.log('parent1');
}

function Child1() {
    Parent1.call(this);
    this.type = 'child1';
}

// 缺点: 只能继承父类构造函数内的属性, 原型链上的内容没有被继承

// 2. 借助原型链实现继承
function Parent2() {
    this.name = 'parent2';
    this.play = [1, 2, 3];
}
Parent2.prototype.say = function () {
    console.log('parent2');
}

function Child2() {
    this.type = 'child2';
}
Child2.prototype = new Parent2();

var s1 = new Child2();
var s2 = new Child2();
s1.play.push(4);

// 缺点: 子类对象的隐式原型都指向同一个对象, 对这个对象的更改会影响所有的子类对象

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

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

Child3.prototype = new Parent3();

// 组合继承的优化1
function Parent4() {
    this.name = 'parent4';
    this.play = [1, 2, 4];
}

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

Child4.prototype = Parent4.prototype;

var s5 = new Child4();
var s6 = new Child4();
console.log(s5 instanceof Child4, s5 instanceof Parent4);
console.log(s5.constructor);

// 缺点: 子类对象的constructor指向了父类, 并且无法用instanceof判断出是有哪一个函数直接构造而成的

// 组合继承的优化2 (完美实现继承)
function Parent5() {
    this.name = 'parent5';
    this.play = [1, 2, 4];
}

function Child5() {
    Parent5.call(this);
    this.type = 'child5';
}

Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
上一篇 下一篇

猜你喜欢

热点阅读