从 javascript 自调用函数中检索 class

Retrieve class from javascript self-invoking function

我有这个功能:

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

我知道 class Test 只能在这种情况下访问。 但我想这样做:

Test.init();

如果我将它存储到一个变量中并这样做:

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

并执行 console.log(t) 它将 return class itself 然后,我可以检索它。但是我不想用那个方法

我想知道,有没有办法从这个 Javascript 自调用函数中检索这个 class? 如果可能,如何实现?

这是我正在使用的 fiddle:http://jsfiddle.net/grnagwg8/

此致,

如果你想让它成为一个全局的,在内联调用的函数中(它不是 self-invoking),分配给 [=14 上的 属性 =]:

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

然后

test.init();

window,在浏览器中,是对全局对象的引用。全局对象的属性是全局变量。

不过,一般来说,最好避免使用全局变量。如果你有不止一个这样的东西,考虑使用一个对象并将它们作为属性放在它上面,这样你只有 one global 而不是 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);

然后

MyStuff.test.init();

您还可以查看 "asynchronous module definition" (AMD) 解决方案。


请注意,在上面的示例中,我使用了 test 而不是 Test压倒性的 JavaScript 中的约定是初始上限标识符用于构造函数,有时 "namespace" 容器对象(它们不是真正的名称空间,但它是一个常见的名称适用于他们)。您的实例不是构造函数,所以...