Search code examples
javascriptself-invoking-function

Retrieve class from javascript self-invoking function


I have this function:

(function(window, document,undefined) {
    'use strict';
    function Test() {
        this.init = function() {
            console.log("init");
        }
    };
    return new Test;
})(window, document);

I know that class Test is only accessible only in this context. But I want to do this:

Test.init();

If I store it into one variable and do like this:

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

and do console.log(t) it will return the class itself and then, I can retrieve it. But I don't want to do that method

I was wondering, is there a way to retrieve this class from this Javascript Self Invoking Functions? How can achieve it, if it is possible?

Here's a fiddle that I'm working with: http://jsfiddle.net/grnagwg8/

Regards,


Solution

  • If you want to make it a global, within the inline-invoked function (it's not self-invoking), assign to a property on window:

    (function(window, document,undefined) {
        'use strict';
        function Test() {
            this.init = function() {
                console.log("init");
            }
        };
        window.test = new Test;  // <====
    })(window, document);
    

    then

    test.init();
    

    window, in browsers, is a reference to the global object. Properties of the global object are global variables.

    In general, though, global variables are best avoided. If you have more than one of these things, consider using an object and putting them on it as properties, so you only have one global rather than many:

    var MyStuff = (function(window, document,undefined) {
        'use strict';
        function Test() {
            this.init = function() {
                console.log("init");
            }
        };
        return {             // <====
            foo: "bar",      // <====
            baz: "nifty",    // <====
            test: new Test   // <====
        };                   // <====
    })(window, document);
    

    then

    MyStuff.test.init();
    

    You might also look at "asynchronous module definition" (AMD) solutions.


    Note that in the above, I used test not Test for the instance. The overwhelming convention in JavaScript is that initially-capped identifiers are for constructor functions and sometimes "namespace" container objects (they're not really namespaces, but it's a common name applied to them). Your instance isn't a constructor function, so...