假设我有两个JavaScript文件,分别是f1.js和f2.js,还有一个名为index.html的HTML页面。
我使用脚本标记来使用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(""),我想使用它。
发布于 2015-12-15 14:26:35
如果您想使用全局模块模式:
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);发布于 2015-12-15 14:09:49
也许这是你想要的
<!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>
发布于 2015-12-15 13:29:16
您需要做的是首先将html链接到f1.js文件,然后将其链接到f2.js文件。这将允许您从f1.js文件调用函数。但是,请确保首先实现f2.js。
https://stackoverflow.com/questions/34290346
复制相似问题