2013-10-21 170 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> 
相關問題