B extends A, but B.add populates A.prototype.property

后端 未结 2 1333
不知归路
不知归路 2021-01-16 10:07

I have one class and another that inherits property children from the first one.

function A() {}
A.prototype.children = [];

function B() {}
B.prototype = ne         


        
2条回答
  •  北海茫月
    2021-01-16 11:03

    You shouldn´t be using the prototype to store data that is for the instance. When you do this.children, there are no children in B, thus the prototype chain continues to A. As suggested by @Bergi, you should remove:

    B.prototype = new A
    

    Try defining:

    function A() {
      this.children = [];
    }
    A.prototype.addChild = function (o) { this.children.push(o)};
    var b = new A();
    b.addChild({});
    

提交回复
热议问题