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

2020-07-03  本文已影响0人  OriX0
组合继承
优势
劣势

: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

优点:
缺点

: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
    }
}

上一篇 下一篇

猜你喜欢

热点阅读