(我是JavaScript新手)。以下代码:
function A() {
console.log('Constructing A');
this.a = new Array();
}
function B(x) {
console.log('Constructing B');
this.a.push(x);
this.b = x;
}
B.prototype = new A();
b1 = new B(10);
b2 = new B(11);
console.log('b1', b1);
console.log('b2', b2);
导致b1和b2共享单个this
.a数组(但不同的this.b
)。这就像一个肤浅的复制品。
我不太明白创建单独this.a
阵列的正确方法是什么。我希望它们被继承,因为这是代码的逻辑,而且我不想在每个子对象中创建它们(在我的例子中有很多子对象)。
我对这个问题的解释很感兴趣。我读过@Niko的重复问题,但似乎这就是区别:
function A() {
console.log('Constructing A');
this.a=new Array();
}
function B(x) {
console.log('Constructing B');
A.call(this); //--> calling the super() constructor creates a new array
this.a.push(x);
}
B.prototype = new A();
b1 = new B(11);
b2 = new B(12);
console.log(b1.a);
console.log(b2.a);
在您的代码中:
> function A() {
> console.log('Constructing A');
> this.a = new Array();
> }
>
> function B(x) {
> console.log('Constructing B');
> this.a.push(x);
> this.b = x;
> }
>
> B.prototype = new A();
这将B的原型设置为A的实例。因此,B的所有实例都将在其[[Prototype]]
链上具有A的实例。
在B构造函数中,this
引用了一个从B.prototype继承的新对象,因此this.a
将引用B.prototype
的a
属性。
> b1 = new B(10);
所以现在B.prototype.a
就是[10]
。
> b2 = new B(11);
现在CCD_ 11是CCD_。