zumzum
zumzum

Reputation: 20138

javascript: call function declared in a different .js file?

I am writing some logic in fileB.js that needs to call another function declared in fileA.js. fileA.js declares a function called abc(). How can I call abc() from fileB.js.

Both fileA and fileB are in the same directory.

Thank you

Ps. I am not using this with HTML. I am just running it locally as part of another project I am working on. I am now using node to run it from terminal. But I am not using anything else in these two files. I just have a bunch of really simple functions. No node.js modules or anything...

Upvotes: 0

Views: 100

Answers (4)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

Node.js isolates each file as a module, giving each their own local scope to define essentially "private" functions and vars.

With this isolation, fileA will need to export abc in order to share it with other files/modules:

function abc() {
    // ...
}

exports.abc = abc;

Then, fileB can require() fileA with a relative path (. referring to the current directory) and use its exported function:

var a = require('./fileA');

a.abc();

Upvotes: 2

SquareFeet
SquareFeet

Reputation: 641

Since you're running it in NodeJS, I'd suggest doing the following at the top of fileB.js:

var fileA = require( './fileA.js' );

However, in order for this to work, the functions you want to use in fileB.js should be exported from fileA.js. To do this, lets assume that the function abc() is what you want to access:

// In fileA.js:
function abc() {
    // ... do something ...
}

module.exports = abc;

If you want multiple functions/variables/objects available to fileB.js, you can export them all as one object:

// In fileA.js
function abc() {
    // ... do something here ...
}

var myObject = {
    propOne: 'foo',
    propTwo: 'bar
};

module.exports = {
    abc: abc,
    myObject: myObject
};

Then, within fileB.js:

// Import the fileA object you just created.
var fileA = require( './fileA.js' );

// Save references to abc and myObject
var myObject = fileA.myObject,
    abc = fileA.abc;

Upvotes: 1

Kuba Jagoda
Kuba Jagoda

Reputation: 5547

If you are using node, then in fileA:

module.exports = { abc: abc } //assuming that abc holds a reference to your function, declared somewhere above

Then, in fileB you require fileA and use what you exported:

var fileA = require('./fileA.js');
fileA.abc();

Upvotes: 1

void
void

Reputation: 36703

Just include both the JS files in the HTML and then simply call them any function anywhere, it will work.

Upvotes: 0

Related Questions