Skip to content Skip to sidebar Skip to footer

How To Create Global, Instance Based Objects From Local Scope?

I have a single global object I use. I know the cons of using global objects but in this case I want to use it. I call this global object the object pipe b.c. it branches my model

Solution 1:

Hold your package privately and just have some access functions:

var myModel = (function() {

    var model_vars = {
        model: 'default',
        result: 'continue',
        page: {},
        args: {},
        server: {},
        hash: localStorage.hash
    };

    returnfunction() {
        this.get = function(ele) {
            if (model_vars.hasOwnProperty(ele)) {
                return model_vars[ele];
            }

        };

        this.set = function(ele, value) {
            if (model_vars.hasOwnProperty(ele)) {
                return model_vars[ele] = value;
            }

        };

    };

})();

Then you can just do:

Model = new myModel();

DEMO: http://jsfiddle.net/maniator/PSsQ3/

Solution 2:

You can pass in the global scope and use it when you need it, something like this:

MC.o_p1 = function(global) {
    return {
        model  :  'default',
        result :  'continue',
        page   :  {},
        args   :  {},
        server :  {},
        hash   :  global.localStorage.hash
        }
}(window);

Solution 3:

var msg = 'window is global in browsers';

window.alert(msg);

alert('or we can just use alert without accessing from window because, '+msg);

functionisWindowReallyGlobalInBrowsers(){
    window.newMsg = 'Did you see var newMsg get declared anywhere?';
    alert(newMsg + ' It works because ' +msg);
}

isWindowReallyGlobalInBrowsers();

Try it in a browser console. Ask questions as needed.

Post a Comment for "How To Create Global, Instance Based Objects From Local Scope?"