Retrieve class from javascript self-invoking function -
i have function:
(function(window, document,undefined) { 'use strict'; function test() { this.init = function() { console.log("init"); } }; return new test; })(window, document); i know class test accessible in context. want this:
test.init(); if store 1 variable , this:
var t = (function() {...})(); and console.log(t) return class itself , then, can retrieve it. don't want method
i wondering, there way retrieve class javascript self invoking functions? how can achieve it, if possible?
here's fiddle i'm working with: http://jsfiddle.net/grnagwg8/
regards,
if want make global, within inline-invoked function (it's not self-invoking), assign 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, reference global object. properties of global object global variables.
in general, though, global variables best avoided. if have more 1 of these things, consider using object , putting them on properties, have one global rather 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 @ "asynchronous module definition" (amd) solutions.
note in above, used test not test instance. overwhelming convention in javascript initially-capped identifiers constructor functions , "namespace" container objects (they're not namespaces, it's common name applied them). instance isn't constructor function, so...
Comments
Post a Comment