(我是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
。一个数组(但不同 this.b
)。这就像一张浅色的副本。
我不太清楚创建单独的 this.a
数组的正确方法是什么。我希望它们继承,因为这是代码的逻辑,除了我不想在每个子对象中创建它们(在我的情况下有很多子对象)。
答案 0 :(得分:3)
我对这个问题的解释很感兴趣。我已经阅读了@ 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);
答案 1 :(得分:0)
在您的代码中:
> 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
将引用a
的{{1}}属性。
B.prototype
所以现在> b1 = new B(10);
是B.prototype.a
。
[10]
现在> b2 = new B(11);
是B.prototype.a
。