(我是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);?
Run Code Online (Sandbox Code Playgroud)
b1和b2中的结果共享单个 this .a数组(但不同 this.b).这就像一张浅色的副本.
我不太明白什么是创建单独 this.a数组的正确方法.我希望它们继承,因为这是代码的逻辑,除了我不想在每个子对象中创建它们(在我的情况下有很多子对象).
在JavaScript中进行继承时,我总是看到的模式定义了原型中的实例方法,但是构造函数中的实例字段(参见下面的示例).这是什么动机?为什么不在原型中保持一致并定义两者?
function MyClass() {
this.myField = 0; // why this...
}
MyClass.prototype.myField = 0; // ...instead of this?
Run Code Online (Sandbox Code Playgroud)