4

メインのhtmlアプリケーションで定義されたスクリプトファイルの順序が重要であることを考慮して、異なる名前空間からのクラスのインスタンスまたはインスタンス変数を相互参照する方法はありますか?実際、2つの異なるクラスインスタンスを相互参照する可能性があるかどうかを知りたいです。1つは異なる名前空間で定義された参照を指し、もう1つは2番目のクラスで定義された変数が最初のインスタンスを指します。

main.js別の名前空間で定義されたいくつかのインスタンス変数を使用するクラスを定義するファイルがあるとします。たとえばparticle.js、で、同時にMainクラスpublic変数を指す変数を定義します。

var Main = (function() {
    var p = new Particle();

    this.draw = true;
    this.width = 800;
    this.height = 600;

    function print() {
        console.log(p.width, ':', p.height);
    }

    return {
        draw : this.draw,
        width : this.width,
        height : this.height,
        print : print
    }
})();

function Particle() {

    this.width = Main.width;
    this.height = Main.height;
    this.print = function() {
        console.log(this.width, ':', this.height);
    }    
}


var p = new Particle();
p.print();
Main.print();

...そして*.htmljavascriptファイルの順序は次のようになります:

<script src = 'main.js'></script>
<script src = 'particle.js'></script>

たとえば、firebugで試してみると、実際にはこのコードは期待どおりに機能していますが、実際のアプリケーションの同じロジックでは非常に複雑で、Main is undefinedコンソールでエラーが発生しました。たとえば、Require.jsでAMDを使用して実際のクラスのモジュールをシミュレートすることは可能ですが、今はAMDで中継したくありません。

4

1 に答える 1

2

ChromeまたはFirefoxでコードを動作させることができませんでした。常にエラーが発生しMain.widthます。

問題は、メインがまだ完全に構築されていないときに、メインの内側のパーティクルを参照することです。

簡単な解決策はありません。Particleクラスを定義した後、メインシングルトンの初期化の一部を遅らせるのが最善だと思います。または、依存関係を尊重するようにコードを並べ替えることもできます。

javascriptでは、コードを呼び出すときにコードが評価されることを覚えておく必要があります。

これが私の2つの提案です:

解決策1:メインの初期化を部分的に遅らせる

// Main.js --> loaded first
var Main = new (function () {
    this.draw = true;
    this.width = 800;
    this.height = 600;

    // delayed initialization method
    this.init = function ()
    {
        var p = new Particle();
        this.print = function () {
            console.log(p.width, ':', p.height);
        }
    }
})();

//Particle.js --> loaded second
function Particle() {
    this.width = Main.width;
    this.height = Main.height;
    this.print = function() {
        console.log(this.width, ':', this.height);
    }    
}

// call the delayed init method
Main.init()

var p = new Particle();
p.print();
Main.print();

解決策2:依存関係を尊重するために3つのファイルに分割する

//Particle.js --> loaded first
function Particle() {
    this.width = Main.width;
    this.height = Main.height;
    this.print = function() {
        console.log(this.width, ':', this.height);
    }    
}

// Main.js --> loaded in second position
var Main = (function() {
    var p = new Particle();
    this.draw = true;
    this.width = 800;
    this.height = 600;
    function print() {
        console.log(p.width, ':', p.height);
    }
    return {
        draw : this.draw,
        width : this.width,
        height : this.height,
        print : print
    }
})();

// Init.js --> loaded third
var p = new Particle();
p.print();
Main.print();
于 2012-07-09T11:38:25.347 に答える