0

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,

2
  • 1
    If you want access to Test don't wrap it in an IIFE ? Commented Jun 1, 2015 at 8:14
  • I know this, but @Crowder has answered my question! :) Commented Jun 1, 2015 at 8:19

1 Answer 1

1

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.