简体   繁体   中英

Can I access a private variable of a Marionette module in a second definition of that module?

Marionette allows you to split the definition of a module across separate files.

Is it somehow possible to access a private variable or function defined in one part of the module from a second part of the module? For example:

//in module1.js
App.module("MyModule", function(MyModule, App, Backbone...){
    myPrivateVar = 0;
}

//in module2.js
App.module("MyModule", function(MyModule, App, Backbone...){
    var myPrivateFunction = function(){
        if (myPrivateVar>0){
            //do something
        }
    }
}

You can not. This is in no way specific to Marionette.

Variables in javascript are function scoped. In other words, any variable declared inside a function is only available within that function.

A common convention for defining faux-private variables (that are actually public) is to prefix the name with an underscore:

//in module1.js
App.module("MyModule", function(MyModule, App, Backbone...){
    MyModule._myPrivateVar = 0;
});

//in module2.js
App.module("MyModule", function(MyModule, App, Backbone...){
    var myPrivateVar = MyModule._myPrivateVar;
    var myPrivateFunction = function(){
        if (myPrivateVar>0){
            //do something
        }
    }
});

The diligence of not accessing _ -prefixed variables from outside the module is up to you. You should also be aware of the loading order of the modules: in order for _myPrivateVar to be defined, module1.js needs to be loaded before module2.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM