Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Isolate this referance in javascript

I am trying to work out a style of javascript modular coding.

Currently I have a "mount variable" declared in a global.js that is linked to all the pages in a web application. It contains global site stuff, like javascript language switching:

var app = window.app || {};

app.Lang = (function ($) {
    "use strict";

    var init = function () {
       ...
        };
    };

    return { init: init };
})($);

app.GlobalLogic = (function ($) {
    "use strict";

    var ready = $(function () {
        app.Lang.init();
    });
}($));

As you can see, I am using immediately executed functions to initialize the logic for a loaded code in the file.

Now I am trying to write an isolated javascript file that can have a similar variable names with other files loaded on the same page. Here is an example:

app.GalleriesAdminLogic = (function ($) {
    "use strict";

    var MountDivID = "#galleries-management-view";

    ...

    var constructorFunction = function () {

        var initialDataObject = $.parseJSON($(MountDivID + " #initial-galleries-list").val());

      ...
}($));

Notice the variable MountDivID. If there was a similar js file loaded at the same time, that would also contain a definition for variable named MountDivID, would it create a resolution conflict? What is the correct pattern to address a same name variables only from local function?

Upvotes: 1

Views: 44

Answers (1)

Pointy
Pointy

Reputation: 413886

Variables declared inside functions are local to that function. They are not visible to other functions, and they "hide" variables with the same name declared outside the function.

Upvotes: 2

Related Questions