简体   繁体   English

使用Iife模式时从另一个js文件调用函数?

[英]Call function from another js file when using iife pattern?

Is it possible to call function that is in one js file and it is made public by usage of iife pattern, in another js file? 是否可以调用一个js文件中的函数,并通过使用iife模式将其公开到另一个js文件中? For example, this is some validationScript.js file: 例如,这是一些validationScript.js文件:

var ValidationNamespace = function () 
{
    var nameValidation = "";
    var testValidation = "";

    return{
        validateIfNameAlreadyExistsInTable : function(currentNameValues)
        {
            for(var i=0; i < currentNameValues.length ; i++)
            {
                if(document.getElementById("tbName").value == currentNameValues[i])
                {
                    var nameVal = "Name already exists in table!";
                    document.getElementById("nameVal").innerHTML = nameVal;
                    return false;
                }
            }
            document.getElementById("nameVal").innerHTML = "";
            return true;
        }
   };
}();

And I have another file, lets say script.js 我还有另一个文件,可以说script.js

Is there some way to call function validateIfNameAlreadyExistsInTable from some script.js function? 有什么方法可以从一些script.js函数调用函数validateIfNameAlreadyExistsInTable吗?

The problem is that it is undefined when I try to call it: 问题是当我尝试调用它时它是不确定的:

在此处输入图片说明

I have index.html where I am referencing both .js files like this: 我有index.html,我在其中引用两个.js文件,如下所示:

<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="validationScript.js"></script>

Yes, because the IIFE returned an object that exposes the function, and the file saves that object as ValidationNamespace , which is a var declared globally and thus a global variable. 是的,因为IIFE返回了一个暴露该函数的对象,并且该文件将该对象另存为ValidationNamespace ,这是全局声明的var ,因此是全局变量。

So: 所以:

ValidationNamespace.validateIfNameAlreadyExistsInTable(theName);

Re your edit, you probably want to load the scripts in the other order, first validationScript.js then script.js : 重新您的编辑,你可能想加载其他顺序执行这些脚本,第一validationScript.js随后script.js

<script type="text/javascript" src="validationScript.js"></script>
<script type="text/javascript" src="script.js"></script>

Scripts are loaded and run in the order you give them (unless you use async or defer ). 脚本按照您指定的顺序加载和运行(除非使用asyncdefer )。 So unless your code in script.js is waiting for some other event, it'll run before validationScript.js is loaded. 所以,除非你的代码script.js正在等待某些其他事件,它会之前运行validationScript.js被加载。

I think this should work. 我认为这应该有效。 ValidationNamespace().validateIfNameAlreadyExistsInTable(theName); ValidationNamespace()。validateIfNameAlreadyExistsInTable(theName);

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

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