0

I'm working on a Javascript module that looks like that.

var myApp = (function(){
    private function1();
    private function2()

    return {
    publicMethod1:function(){}
    publicMethod2:function(){}
    publicMethod3:function(){}
    }
})();
myApp.publicMethod3();

My module will maybe be used in a tag container, I'm not really sure about how that work but I'm afraid if for example, my module is executed in a global autoexecuted function, like this :

(function(){

var myApp = (function(){
    private function1();
    private function2()

    return {
    publicMethod1:function(){}
    publicMethod2:function(){}
    publicMethod3:function(){}
    }
})();
myApp.publicMethod3();
})();

I can't execute the methode of my module like I did before, my code won't work inside.

So what I'm asking? Do you know how work tag container? And, if the tag container includes my code in a global auto executed function, how could I change my module's code to make it working well inside. Thanks for your answers, and if is not clear to you, I'm gonna answer quickly to your questions.

4

2 に答える 2

1

コードが IIFE 内で定義されたときにコードが機能しなくなることが心配な場合は、モジュールがウィンドウ オブジェクトのグローバル プロパティであることを確認するしかありません。

// append it to the window instead of using var
// this way it will always be global and not constrained to any wrapping scopes
window.myApp = (function(){
   ...
})();

ウィンドウ オブジェクトにプロパティを追加すると、すぐに厄介になる可能性があることに注意してください。これを一度だけ実行し、myAppオブジェクトの下に他のすべてのコードを公開するようにしてください。

于 2013-01-29T13:43:32.200 に答える
0

コードに一連の構文エラーがありました。これを試してください:

(function(){
    var myApp = (function(){
        var function1 = function(){};   // Fixed function declaration
        var function2 = function(){};

        return {
            publicMethod1:function(){}, // Added missing comma's
            publicMethod2:function(){},
            publicMethod3:function(){}
        }
    })();
    myApp.publicMethod3();
})();

JavaScript にはキーワードがなくprivate、関数は次のように宣言する必要があります。

var name = function(){/* function body here */};

// or 
function name(){/* function body here */}

// or, when declared in objects:
var someObject = {
    name: function(){/* function body here */}
}

また、オブジェクト内のアイテムは、次のようにコンマで区切られます。

var someObject = {
    property1: "value 1",
    property2: "value 2",
    property3: true,
    property4: 1234,
    property5: 1234   // Note: no comma after the last property.
}
于 2013-01-29T13:33:42.107 に答える