user1930227
user1930227

Reputation: 105

How can I reuse code from one JavaScript file in another?

Say I had 2 JavaScript files, f1.js and f2.js respectively and one HTML page called index.html.

I use the script tag to use the code from f1.js in my index.html. But, I want f1.js to use some code from f2.js. So, the hierarchy is like this - index.html <--- f1.js <--- f2.js.

i.e. f2.js is a pseudo-random generator and has a function which creates a random seed, and I want to use this in my code for f1.js.

Code example:

index.html - how I call f1.js in the html page (my code)

<script type="text/javascript" src="f1.js">
</script> 

f1.js - my code

function hello() {
    Math.seedrandom("1"); // this is the method I want to reuse from f2.js
    alert("hello: " + Math.random());
}

f2.js - code I want to use (via the link below)

Math.seedrandom();

How can I do this?

Edit: the file I want to reuse can be found her - http://davidbau.com/encode/seedrandom.js

It's a custom random seed generator tool which has a function: Math.seedrandom("") that I want to use.

Upvotes: 5

Views: 3242

Answers (3)

Daniel Lizik
Daniel Lizik

Reputation: 3144

If you want to use a global module pattern:

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

If you don't like this pattern, look into require.js, or a backend bundler like browserify or webpack.

The global module pattern might be used more like this, however.

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);

Upvotes: 3

ujeenator
ujeenator

Reputation: 28586

Maybe this what you want:

<!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>

Upvotes: 1

Rishi
Rishi

Reputation: 419

What you need to do is, link the html to the f1.js file first, and then link it to the f2.js file. This will allow you to call the function from the f1.js file. But make sure to implement f2.js first.

Upvotes: -1

Related Questions