JavaScript scope between script tags

I have two different JSPs that the Java server combines together and sends back to the same displayed HTML page.

Each JSP has its own <script> block and defines functions inside this block:

JSP # 1:

 <script type="text/javascript"> function blah() { ... } </script> 

JSP # 2

 <script type="text/javascript"> function foo() { blah(); } </script> 

As I said, the backend adds them to the HTTP response and sends them back to the browser during the same request.

When I launch this page in my browser, I can immediately say that blah() not executed when foo() called. I see that the console error in Firebug with blah() not defined. I am wondering if blah() only has an area inside its <script> , and also for foo() . Is this the case here or is something else wrong?

When I turn to viewing the source of the page, I see both script blocks and both functions. This tells me that everything is generated / displayed correctly on the server side, but perhaps my approach is inherently wrong (defining functions inside different script tags). Thanks in advance.

+6
source share
3 answers

they are all global. they can see each other. the problem is when they are defined and called each other.

you must define and call them in the following order:

  • bar
  • Foo
  • call foo
    • Done foo and call bar
    • performed
+5
source

You can call the function as follows:

  (function($) { var namespace; namespace = { something : function() { alert('hello there!'); }, bodyInfo : function() { alert($('body').attr('id')); } }; window.ns = namespace; })(this.jQuery); $(function() { ns.something(); ns.bodyInfo(); }); 
+1
source

The only thing that defines the scope in JavaScript is the function, so your problem is not a problem. You most likely don't call foo (), you call it before blah () is defined, or you have a syntax error somewhere. Perhaps you can post your entire HTML page so that we can see what is happening.

0
source

Source: https://habr.com/ru/post/913994/


All Articles