JavaScript:继承

JavaScript:继承,javascript,oop,prototypal-inheritance,Javascript,Oop,Prototypal Inheritance,我试图进行继承,但没想到this.array会像静态成员一样工作。如何将其设置为“受保护/公开”: function A() { this.array = []; } function B() { this.array.push(1); } B.prototype.constructor=B; B.prototype = new A(); 萤火虫: >>> b = new B(); A { array=[1]} >>> b = new B(

我试图进行继承,但没想到
this.array
会像静态成员一样工作。如何将其设置为“受保护/公开”:

function A() {
    this.array = [];
}

function B() {
    this.array.push(1);
}
B.prototype.constructor=B;
B.prototype = new A();
萤火虫:

>>> b = new B();
A { array=[1]}
>>> b = new B();
A { array=[2]}
>>> b = new B()
A { array=[3]}
不是“私有/受保护”,但这将为每个
B
创建一个新数组

function A() {
    this.array = [];
}

function B() {
    A.apply(this); // apply the A constructor to the new object
    this.array.push(1);
}
// B.prototype.constructor=B; // pointless
B.prototype = new A();

顺便说一句,你的最后两行是向后的。设置
prototype.constructor
之后,设置
prototype.constructor
。我知道这只是一个示例,但为什么不改为
this.array=[1]
?原始代码看起来像:函数控制器(uri){this.\u controllerURI=uri;this.\u控制器=[];this.\u视图=[];this.\u事件=[];}。这只是一个例子。我想你的意思是
a.call(this)@user(\d)*完美。谢谢@minitech:可以应用-它很有效。在哪里可以找到您的$Query替换的文档/示例代码?