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

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

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

    相关文章

      网友评论

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

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