2013-10-21 166 views
1

我目前正在使用JavaScript来尝试和理解更多的语言。我想制作两个不同的模块,一个使用通用帮助器功能,另一个使用特定的功能来解决问题。JavaScript'将一个模块导入到另一个模块中

如何从一个模块访问另一个模块的功能?

+1

那么单词“模块”在JavaScript中没有官方含义,所以你必须解释你有什么。实现类似“模块”的方法有很多种。 – Pointy

+0

如果你在Stack Overflow中查找相关的问题,我相信你能找到答案。 –

+0

如何: http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file –

回答

1

您有两种选择。两者都相当受欢迎,所以这取决于你选择哪个。

首先是在你的应用程序模块的父的范围来定义您的帮助模块:

var helpMod = (function(){ 
    return {foo:"bar"} 
})(); 

var appMod = (function(){ 
    console.log(helpMod.foo); 
})() 

而第二个是直接导入模块作为参数传递给关闭功能:

var helpMod = (function(){ 
    return {foo:"bar"} 
})(); 

var appMod = (function(h){ 
    console.log(h.foo); 
})(helpMod); 

直接导入更明确,但利用范围确定可以更容易 - 只要您对全局范围内的变量感到满意!

0

你会简单地将各种功能分成两个独立的文件,然后在 “沙箱” 的HTML页面中引用它们如下:

helper.js

function helper_function() { 
    alert("this is a helper function"); 
} 

specific.js

function specific_function() { 
    alert("this is a specific function"); 
} 

index.html

<html> 
<head> 
    <script src="helper.js"></script> 
    <script src="specific.js"></script> 
</head> 


<body> 

<script type="text/javascript"> 
    helper_function(); 
    specific_function(); 

</script> 
</body> 
</html> 
相关问题