简体   繁体   English

在IIFE中访问构造函数

[英]Accessing constructor within an IIFE

Often, in JavaScript, I see an anonymous function, which is immediately invoked, that contains a constructor function. 通常,在JavaScript中,我会看到一个匿名函数,该函数立即被调用,其中包含一个构造函数。 Something like this: 像这样:

(function(){
    function Constructor{};
    //code and stuff
})();

This seems beneficial because it makes a Closure (?), so you can keep the variables within the function seperate from the Global Scope. 这似乎是有益的,因为它使一个闭包(?),因此您可以将函数内的变量与全局范围分开。 What I'm having trouble understanding is how would I access this constructor from within the Global Scope. 我无法理解的是如何从Global Scope中访问此构造函数。 For instance, say the code above is contained in a JavaScript file which is brought into an HTML document with the script tag. 例如,假设上面的代码包含在一个JavaScript文件中,该文件通过script标签带入HTML文档。 Now, in the document (within another script tag) how can I instantiate an Object using the constructor in the anonymous function? 现在,在文档中(在另一个脚本标签中)如何使用匿名函数中的构造函数实例化对象?

As you have stated, the main purpose of an immediately invoked function is to prevent the pollution of the Global scope. 如您所述,立即调用函数的主要目的是防止Global范围的污染。 Therefore, all the variables and functions declared within an IIFE can only be accessed within that function. 因此,IIFE中声明的所有变量和函数只能在该函数中访问。

As I understand from your example, you are trying to modularize your application and separate your various application logic into different script files. 从您的示例中可以理解,您正在尝试对应用程序进行模块化,并将各种应用程序逻辑分离到不同的脚本文件中。 I would recommend that you take a look at the Module Pattern: 我建议您看一下“模块模式”:

var Module1 = (function() {

    return {
        Constructor: function Constructor(){
            console.log('Hi, there!');
        }
    }
})();

Then, you could simply access the Constructor function using the following code: 然后,您可以使用以下代码简单地访问Constructor函数:

var test = Module1.Constructor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM