js继承的最终形式是下面那种对吗?

//组合继承

  • 最终版本,互不干扰,属性共享,方法共用,两两不交叉
  • 但是下面有个缺陷的地方是做了两次构建,导致如下的继承关系。
//组合继承
let log = a=>{console.log(a)}
function Person(){
    this.a = ["a"];
}
Person.prototype.b=["b"];
function Myth(){
    Person.call(this)
    this.c = ["c"];
}
Myth.prototype=new Person();
Myth.prototype.constructor=Myth;
Myth.prototype.d=["d"];
let myth1 = new Myth();
log(myth1);

图片描述

还有一种 我认为 这种才是最终版本~

//寄生组合继承

  • 其实我这里简化了寄生的过程 变成了赋值的操作 父子的构造器属性私有,原型共享,各自构造器是本身 完美~
function Person(){
    this.a = ["a"];
}
Person.prototype.b=["b"];
function Myth(){
    Person.call(this)
    this.c = ["c"];
}
Myth.prototype=Person.prototype;
Myth.prototype.constructor=Myth;
Myth.prototype.d=["d"];
let myth1 = new Myth();
log(myth1);

图片描述

你们觉得呢???

阅读 2.5k
2 个回答

这么写你原型里的数组不是共用了么

    function Person() {
      this.a = ["a"];
    }
    Person.prototype.b = ["b"];

    function Myth() {
      Person.call(this)
      this.c = ["c"];
    }
    Myth.prototype = Person.prototype;
    Myth.prototype.constructor = Myth;
    Myth.prototype.d = ["d"];
    let myth1 = new Myth();
    let myth2 = new Myth();
    myth1.b.push("2");
    log(myth1);
    log(myth2);
    console.log(Person.prototype)

你改了子类的原型,父类原型都给改了.

这跟直接继承 new Person()有什么区别....

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题