美文网首页
如何避免原型链上的对象共享

如何避免原型链上的对象共享

作者: OriX0 | 来源:发表于2020-07-03 21:46 被阅读0次
组合继承
优势
  • 公有的写在原型
  • 私有的卸载构造函数
  • 可以向父类传递参数
劣势
  • 需要手动绑定constructor
  • 封装性一般
  • 重复调用父类性能损耗

:chestnut:

function Parent (name, friends) {
  // 私有的部分
  this.name = name;
  this.friends = friends;
}
Parent.prototype = {
  // 公有的写这里
  constructor: Parent,// 需要手动绑定
  share: [1, 2, 3],
  log: function () {
    return this.name;
  }
}

// 封装性一般
function Child (name, friends, gender) {
  Parent.call(this, name, friends); // 这里调用了一次Parent
  this.gender = gender;
}
Child.prototype = new Parent(); // 这里又调用了一次Parent
Child.prototype.constructor = Child;//需要手动修改constructor
寄生组合继承
寄生组合式继承

杂糅了原型链式、构造函数式、组合式、原型式、寄生式而形成的一种方式:

主要是解决了组合继承的唯一缺点:多次调用Parent

优点:
  • 公有的写在原型
  • 私有的写在构造函数
  • 可以向父类传递参数
  • 不会重复调用父类
缺点
  • 需要手动绑定constructor
  • 需要调用额外的方法 封装性一般

:chestnut:

function Parent (name, friends) {
  this.name = name;
  this.friends = friends;
}
Parent.prototype = {
  constructor: Parent,//需要手动绑定constructor
  share: [1, 2, 3],
  log: function () {
    return this.name
  }
}
function Child (name, friends, gender) {
  Parent.call(this, name, friends);
  this.gender = gender;
}
function proto(child, parent) {
  let clonePrototype = Object.create(parent.prototype)
  child.prototype = clonePrototype
  child.prototype.constructor = child
}
proto(Child,Parent);
ES6 class

:chestnut:

class Parent {
    constructor(name, friends) { // 该属性在构造函数上,不共享
        this.name = name
        this.friends = friends
    }
    log() { // 该方法在原型上,共享
        return this
    }
}
Parent.prototype.share = [1, 2, 3] // 原型上的属性,共享

class Child extends Parent {
    constructor(name, friends, gender) {
        super(name, friends)
        this.gender = gender
    }
}

相关文章

  • 如何避免原型链上的对象共享

    组合继承 优势 公有的写在原型 私有的卸载构造函数 可以向父类传递参数 劣势 需要手动绑定constructor ...

  • JS继承理解

    1、原型链继承: 共享父类(实例)属性方法 原型链继承:优点:能够共享父类属性和方法,避免每个实例重新定义方法属性...

  • JS继承

    继承的概念:子类可以使用父类共享的属性和方法,避免重复代码提高代码复用性。 原型链:子类可以共享父类的实例对象和实...

  • js原型和原型链

    什么是原型 .什么是原型链? 原型:对象上的内置属性[[prototype]] 原型链:在对象上访问某个属性,如果...

  • JavaScript进阶:原型模式

    1、前言 原型模式是指的将原型对象指向创建对象的类,使得不同的类共享原型对象的方法和属性。js中基于原型链的继承的...

  • 谈谈 js 原型链

    原型链是为了实现继承,也就是说js的继承是基于原型链的。原型-prototype,是一个对象,用于存放共享的属性和...

  • JS原型02之原型链

    1.如何构成原型链2.原型链上属性的增删改查原型链上的增删改查和原型一致,只有本人能操作3.绝大多数对象最终会继承...

  • js集成

    原始继承模式--原型链 2:借用构造函数 3:共享构造原型 4:圣杯模式原型链; 构造函数; 共享原型; 圣杯模式...

  • 如何理解原型与原型链

    题目如何理解原型与原型链? 参考答案 构造函数有个prototype对象(原型),该对象有个“constructo...

  • 📕 原型对象

    基本概念 原型 每一个对象都有它的原型对象,可以使用自己原型对象上的所有属性和方法 原型链 对象有原型,原型也是对...

网友评论

      本文标题:如何避免原型链上的对象共享

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