从另一个Javascript文件调用IIFE [英] Call IIFE From Another Javascript File
问题描述
我有一个文件bg.js
,其内容只是一个IIFE.我想加载此文件/从另一个文件中的另一个函数调用该函数.由于IIFE是匿名的(是吗?),我不能用名字来称呼它.看来我必须加载整个文件,这样它才能立即执行.
I have a file bg.js
whose contents is simply an IIFE. I'd like to load this file/call the function in from another function in another file. Since the IIFE is anonymous (it is, right?) I can't call it by name. It seems I have to load the entire file so it executes immediately.
我已经进行了搜索,找到了很多关于IIFE是什么的教程和文档,但是我从没见过如何从另一个范围执行一个.
I've done searching and found many tutorials and documents about what an IIFE is, but nowhere had I seen how to execute one from another scope.
如何从另一个JavaScript文件调用/加载一个IIFE的JavaScript文件?
How do I call/load a javascript file that is an IIFE from another javascript file?
更多信息
IIFE已加载到我页面的页脚中.当我单击链接进行导航时,不执行页眉和页脚脚本.页脚中的IIFE负责设置背景图片,因此我需要在perPageBindings()
More Information
The IIFE is loaded in the footer of my page. When I click a link to navigate, the header and footer scripts are not executed. The IIFE in the footer is responsible for setting the background image, so I need to get that function to execute in my perPageBindings()
我想我需要做的是从主体中的另一个函数调用IIFE,该函数在perPageBindings()
What I think I need to do is invoke the IIFE from another function in the body which is being executed in perPageBindings()
为清楚起见 我正在考虑两种选择:
Edit for clarity There are two options I am considering:
- 只需将脚本标签从页脚移动到正文;或
- 给IIFE指定一个名称,这样它就不再是匿名的,然后从其他地方调用该命名函数
如果2是一个可行的选择,那么我想我将创建一个有关将IIFE和IIFE转换为命名函数的新问题.
If 2 is a viable option then I think I will create a new question about converting and IIFE to a named function.
推荐答案
如果要在匿名调用后访问该脚本,函数或属性中的某些内容,则需要公开一些内部信息可以从全局范围访问的功能.
If you want to access something within that script, a function or a property, after it has been anonymously invoked, you'll need to expose some of the internals of that function to something that is accessible from global scope.
我并不是说您必须让函数将变量放入全局范围,尽管这是许多库所做的工作,并且是UMD
遵循的路径之一,如果CommonJS
或AMD
环境是不可用.
I'm not saying that you must have your function put a variable into global scope, although that is what many libraries do and is one of the paths that UMD
follows if a CommonJS
or AMD
environment is not available.
您应该查看显示模块模式以获得更好的视角.
You should look into the Revealing Module Pattern for a better perspective.
请考虑以下代码段:
(function(global){
/*
* This variable will stay "private"
* because it is scoped to the IIF
*/
var someProp = "Hello World";
/*
* This property is effectively exposed
* because it is accessible through
* myLib.foxtrot below
*/
var someOtherProp = "Hello to you too";
var myLib = {
foo: "bar",
fiz: true,
buzz: 1,
foxtrot: someOtherProp
};
/*
* myLib is now accessible through the
* global that we passed to the IIF below
* at the point of calling with "window"
*/
global.myLib = myLib;
}(window));
这篇关于从另一个Javascript文件调用IIFE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!