[英]How can I reuse code from one JavaScript file in another?
假設我有2個JavaScript文件,分別為f1.js和f2.js,以及一個名為index.html的HTML頁面。
我使用script標簽在index.html中使用f1.js中的代碼。 但是,我希望f1.js使用f2.js中的一些代碼。 因此,層次結構就是這樣-index.html <--- f1.js <---f2.js。
即f2.js是偽隨機數生成器,並且具有創建隨機種子的函數,我想在我的代碼中將其用於f1.js。
代碼示例:
index.html-我如何在html頁面中調用f1.js(我的代碼)
<script type="text/javascript" src="f1.js">
</script>
f1.js-我的代碼
function hello() {
Math.seedrandom("1"); // this is the method I want to reuse from f2.js
alert("hello: " + Math.random());
}
f2.js-我要使用的代碼(通過下面的鏈接)
Math.seedrandom();
我怎樣才能做到這一點?
編輯:我想重用的文件可以找到她-http://davidbau.com/encode/seedrandom.js
這是一個自定義隨機種子生成器工具,具有以下功能:我要使用的Math.seedrandom(“”)。
如果要使用全局模塊模式:
的index.html
<head>
<script src="f1.js"></script>
<script src="f2.js"></script>
</head>
f1.js
function hello() {
//some stuff
}
f2.js
(function(privateHello) {//now it's private
privateHello(); //invoke private instance
})(hello); //inject global variable
如果您不喜歡這種模式,請查看require.js或后端捆綁程序,例如browserify或webpack。
但是,可以更像這樣使用全局模塊模式。
f1.js
var _functions = (function() {
return {
fn_a: function() { /* do something */ },
fn_b: function() { /* do something else */ }
};
})();
fs2.js
(function(methods) {
methods.fn_a(); //do something
methods.fn_b(); //do something else
})(_functions);
也許這就是你想要的:
<!DOCTYPE html> <script src=//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.3.10/seedrandom.min.js> </script> <script> function hello(){ Math.seedrandom("1"); alert("hello: " + Math.random()); } </script> <button onclick="hello()">Run seedrandom</button>
您需要做的是先將html鏈接到f1.js文件,然后再將其鏈接到f2.js文件。 這將允許您從f1.js文件中調用該函數。 但是請確保首先實現f2.js。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.