-2

I am trying to call a new function under existing function. First function works perfectly, but code does not go inside test function. Any idea on this issue?

The error I get on this is : test is not defined

var doIt;
var test;

$(document).ready(function() {
  test(2);
  doIt = function() { //now has global scope.
    test(1);
  };

  test = function(n) {
    alert('test function');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <input name="Go" type="button" value="Go" onclick="doIt();" />
</body>
Cristal
  • 481
  • 4
  • 14

1 Answers1

1

You just have to define things on the correct places.

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
      var doIt;
      var test;

      $(document).ready(function()
      { 
         // You can't invoke test variable here since it has been declared
         // but not yet initialized.
         // test(2);
         // If you had declared a function instead, like the test2(),
         // then it would be in the scope of the whole document
         test2();

         doIt = function() {
          test(1);
         };

         test = function(n){
            alert('test function');
         };

         //you could invoke it here though, after it has been initialized 
         test(2);
      });
      function test2(){
         alert('test2 function');
      }
    </script>
  </head>
  <body>
    <input name="Go" type="button" value="Go" onclick="doIt();"/>
  </body>
</html>

Note you are not declaring a function anywhere. Instead you are declaring a variable and initializing it with a function later, so you have to respect the variable's scope

Gus
  • 899
  • 9
  • 29