[英]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.