locked
Call one JS file function into another JS file function RRS feed

  • Question

  • User430178104 posted

    Hi, I have 2 javasctipt files both are having functions. I need to call the one file function into another by passing parameters, and same vice versa.

    but this is not working, getting method not defined error

    Thursday, May 27, 2021 5:11 PM

All replies

  • User475983607 posted

    Hi, I have 2 javasctipt files both are having functions. I need to call the one file function into another by passing parameters, and same vice versa.

    but this is not working, getting method not defined error

    Calling a function is a very straight forward.  Can you share code that illustrates the problem you are facing.  Otherwise, perhaps browser the JavaScript reference documentation see if you find an answer to your question.

    https://www.w3schools.com/js/js_functions.asp

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

    Thursday, May 27, 2021 6:40 PM
  • User753101303 posted

    Hi,

    I gave this a try with the simplest example I could and it seems to work. For example using in separate files::

    function a(i)
    {
      alert("a"+i);
      if (i<5) b(i+1);
    };
    
    function b(i)
    {
      alert("b"+i);
      if (i<5) a(i+1);
    };
    

    Still I would avoid this and I'm not sure I ever even thought trying this before.

    Avoid posting big pieces of code but try perhaps to reproduce what doesn't work with the smallest files you can? Either you'll find yourself the issue during this or you'll have something to show that others could look at?

    If you psot long files without even trying to narrow down the problem, it is less likely that someone will go through numerous line to spot the few lines causing the actual issue.

    Friday, May 28, 2021 1:18 AM
  • User1535942433 posted

    Hi pathipati,

    The function could be called as if it was in the same JS File as long as the file containing the definition of the function has been loaded before the first use of the function.

    A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

    A function cannot be called unless it is in the same or greater scope then the one trying to call it.

    File1.js:

    function alertNumber(number) {
        alert(number);
    }

    File2.js:

    function alertOne() {
         alertNumber("one");
    }
    <head>
    ....
        <script src="File1.js" type="text/javascript"></script> 
        <script src="File2.js" type="text/javascript"></script> 
    ....
    </head>
    <body>
    ....
        <script type="text/javascript">
           alertOne();
        </script>
    ....
    </body>

    Best regards,

    Yijing Sun

    Friday, May 28, 2021 2:30 AM