美文网首页
Js中的几种继承方式?

Js中的几种继承方式?

作者: 风雅欢乐 | 来源:发表于2020-05-11 20:38 被阅读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;

相关文章

  • JavaScript 继承

    继承是JS中非常内容,原因就是JS没有地道的继承方式,我们只能通过各种方式来模拟面向对象中的继承。下面介绍几种常见...

  • Js中的几种继承方式?

    直接从代码中看

  • 聊一聊js的几种继承方式

    在js中, 很多地方需要使用到继承, 废话少说, 今天来聊一聊js几种继承方式的优缺点 构造函数继承functio...

  • js几种继承方式

    注意: 1,constructor总是指向类的构造函数 2,__proto__指向父类的原型对象 1,原型链继承 ...

  • JS中关于继承的几种方式

    继承基本概念 继承的概念 继承:即通过一定的方式实现让某个类型A获取另外一个类型B的属性或方法。其中类型A称之为子...

  • JS继承的几种方式

    关于Js继承的几种方式,总结一下,以便查看。 第一种 prototype 引用型原型继承 语言支持:js原生支持的...

  • JS继承的几种方式

    JS继承的几种方式 (1) 属性拷贝 存在问题: 如果继承过来的成员是引用类型的话,那么这个引用类型的成员在父对象...

  • js继承的几种方式

    1 原型链继承 把子类的prototype指向父级的实例,也就是原型链继承 此继承方法优 简单明了,父级新增的属性...

  • js继承的几种方式

    在我近三年的职业生涯中,老实说,我很少需要自己去写一个类,然后继承,然后如何如何去调用这些方法,除了有一次公司紧急...

  • js中的实现继承的几种方式

    大纲:原型链借用构造函数组合继承原型式继承寄生式继承寄生组合式继承 1、原型链: 什么是原型链? 原型链的基本思想...

网友评论

      本文标题:Js中的几种继承方式?

      本文链接:https://www.haomeiwen.com/subject/blppnhtx.html