Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  0] [ 3]  / answers: 1 / hits: 16953  / 12 Years ago, fri, february 8, 2013, 12:00:00

I'm just a bit confused here... If I have one .js file with function like this:



function myMain() {
var count=0;
count++;
myHelper(count);
alert(count);
}

function myHelper(count) {
alert(count);
count++;
}


Can I still call another method myHelper() on the other .js file? Or is there any other way that I can pass the count variable from one function to another then it will be called to other .js file. Do you have any idea regarding this one? Thanks!


More From » function

 Answers
4

Update: Nowadays you should prefer to use ES6 import/export in a <script> tag with type=module or via a module bundler like webpack.






When both script files are included in the same page, they run in the same global JavaScript context, so the two names will overwrite each other. So no, you can not have two functions in different .js files with the same name and access both of them as you've written it.



The simplest solution would be to just rename one of the functions.



A better solution would be for you to write your JavaScript modularly with namespaces, so that each script file adds the minimum possible (preferably 1) objects to the global scope to avoid naming conflicts between separate scripts.



There are a number of ways to do this in JavaScript. The simplest way is to just define a single object in each file:



// In your first script file
var ModuleName = {
myMain: function () {
var count=0;
count++;
myHelper(count);
alert(count);
},

myHelper: function (count) {
alert(count);
count++;
}
}


In a later script file, call the function
ModuleName.myMain();



A more popular method is to use a self-evaluating function, similar to the following:



(function (window, undefined) {

// Your code, defining various functions, etc.
function myMain() { ... }
function myHelper(count) { ... }

// More code...

// List functions you want other scripts to access
window.ModuleName = {
myHelper: myHelper,
myMain: myMain
};
})(window)

[#80357] Wednesday, February 6, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
whitney

Total Points: 642
Total Questions: 110
Total Answers: 98

Location: Solomon Islands
Member since Mon, Jun 20, 2022
2 Years ago
;