2

私はMozillaがコンストラクタチェーンに出すコードを理解しようとしています。私が理解していると思う部分にコメントを追加しましたが、ここで起こっていることすべてについてはまだはっきりしていません。誰かがこのコードで何が起こっているのかを行ごとに説明できますか?

// Using apply() to chain constructors.
Function.prototype.construct = function (aArgs) {

    // What is this line of code doing?
    var fConstructor = this, fNewConstr = function () { fConstructor.apply(this, aArgs); };

    // Assign the function prototype to the new function constructor's prototype.
    fNewConstr.prototype = fConstructor.prototype;

    // Return the new function constructor.
    return new fNewConstr();
};

// Example usage.
function MyConstructor () {

    // Iterate through the arguments passed into the constructor and add them as properties.
    for (var nProp = 0; nProp < arguments.length; nProp++) {
        this["property" + nProp] = arguments[nProp];
    }
}

var myArray = [4, "Hello world!", false];
var myInstance = MyConstructor.construct(myArray);

// alerts "Hello world!"
alert(myInstance.property1); 

// alerts "true"
alert(myInstance instanceof MyConstructor); 

// alerts "MyConstructor"
alert(myInstance.constructor); 

元のコードはここにあります。

4

1 に答える 1

2

基本的に、これはコンストラクター関数を呼び出す別の方法であり、コンストラクター呼び出しを別の関数でラップする機会を提供します。私はあなたが混乱している線に焦点を合わせます。 fConstructorはに設定されます。thisこれは、元のコンストラクター関数を参照します。この例では、ですMyConstructorfNewConstr元のコンストラクターをオーバーライドするコンストラクターです。その中で、fNewConstrにない追加のコードを実装できますMyConstructor。内では、関数applyメソッドを使用しfNewConstrて呼び出し、コンテキストとして渡し、配列をconstructメソッドに渡します。次に、のプロトタイプをに設定しますfConstructorthisaArgsfNewConstrfConstructor継承チェーンを完成させるためのプロトタイプ。最後に、の新しいインスタンスを返しますfNewConstr。関数呼び出しの前にnewキーワードを付けると、新しいオブジェクトが作成され、そのプロトタイプが関数のプロトタイプに設定され、新しいアイテムのコンテキストで関数が呼び出されます。fConstructor'sコンテキストを使用してメソッドを適用するためfNewConstr、結果は基本的に。を呼び出すのと同じnew MyConstructor()です。わかる?それとも、もっと詳しく説明する必要がありますか。

于 2012-10-17T21:05:31.387 に答える