0

我有这个功能:

(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)会返回class itself然后,我可以检索它。但我不想这样做

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

这是我正在使用的小提琴:http: //jsfiddle.net/grnagwg8/

问候,

4

1 回答 1

1

如果你想让它成为一个全局的,在内联调用的函数中(它不是调用的),分配给一个属性 on window

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

然后

test.init();

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

不过,一般来说,最好避免使用全局变量。如果你有不止一个这些东西,考虑使用一个对象并将它们作为属性放在它上面,这样你就只有一个全局而不是多个:

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();

您还可以查看“异步模块定义”(AMD)解决方案。


请注意,在上面,我test没有Test用于实例。JavaScript中压倒性的约定是初始上限标识符用于构造函数,有时用于“命名空间”容器对象(它们不是真正的命名空间,但它是应用于它们的通用名称)。您的实例不是构造函数,所以...

于 2015-06-01T08:14:10.383 回答