[js] js怎样避免原型链上的对象共享?

组合继承
优势

公有的写在原型
私有的卸载构造函数
可以向父类传递参数

劣势

需要手动绑定constructor
封装性一般
重复调用父类性能损耗

🌰

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
需要调用额外的方法 封装性一般

🌰

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

🌰

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

个人简介

我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论

主目录

与歌谣一起通关前端面试题