Calling a function with the same name in another JS file

I'm just a little confused here ... If I have one .js

file with a 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 a different .js file? Or is there another way I can pass the count variable from one function to another, then it will be called in another .js file. Do you have any ideas regarding this? Thank!

+3


source to share


3 answers


Update: now you prefer to use ES6 import

/ export

tag <script>

with type="module"

or through a package of modules, such as a Web package .


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 cannot have two functions in different .js files with the same name and access both of them as you wrote them.

The simplest solution is to simply rename one of the functions.

A better solution would be to write your JavaScript modularly with namespaces so that each script file adds the smallest possible (preferably 1) objects to the global scope to avoid name conflicts between individual scripts.



There are several ways to do this in JavaScript. The easiest way is to just define one 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-assessment 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)

      

+15


source


If you know that you are going to overwrite the method, you can first store the old one in a variable and then call another function implementation through that variable.



-3


source


Yes, you can call myHelper () from any other js file as long as you include both js files in one html or jsp page

you can look at this: Is it possible to call a function written in one JavaScript in another JS file?

-4


source







All Articles