5

(私は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配列を作成する正しい方法が何であるかがよくわかりません。これはコードのロジックであるため、継承したいのですが、すべての子オブジェクトでそれらを作成したくないことに加えて (私の場合は多くの子オブジェクトがあります)。

4

2 に答える 2

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);
于 2012-08-26T12:35:01.673 に答える
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();

[[Prototype]]これにより、BのプロトタイプがAのインスタンスとして設定されます。したがって、Bのすべてのインスタンスは、チェーン上にAのそのインスタンスを持ちます。

Bコンストラクターで、thisB.prototypeから継承する新しいオブジェクトを参照するため、のプロパティをthis.a参照します。aB.prototype

> b1 = new B(10);

だから今B.prototype.aです[10]

> b2 = new B(11);

そして今B.prototype.a[10, 11]です。

于 2012-08-26T13:21:10.100 に答える