JavaScript function scope between script tags
Solution 1
all of them are global. they can see each other. the problem is when they get defined and call each other.
you should define and call them in this order:
- bar
- foo
- call foo
- foo executed and calls bar
- bar is executed
Solution 2
You can call function like this:
(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();
});
IAmYourFaja
my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.
Updated on July 03, 2022Comments
-
IAmYourFaja almost 2 years
I have two different JSPs that the Java backend concatenates together and sends back to the same rendered HTML page.
Each JSP has its own
<script>
block and defines functions inside that block:JSP #1:
<script type="text/javascript"> function blah() { ... } </script>
JSP #2
<script type="text/javascript"> function foo() { blah(); } </script>
Like I said, the backend adds these to the HTTP response and sends them back to the browser during the same request.
When I run this page in my browser, I can tell right away that
blah()
is not executing whenfoo()
is getting called. I see a console error in Firebug statingblah()
is not defined. I'm wondering ifblah()
only has scope inside its own<script>
tag, and likewise forfoo()
. Is that the case here, or is something else awry?When I go to view the page source I see both script blocks and both functions. This tells me everything is being generated/rendered correctly server-side, but perhaps my approach is inherently wrong (defining the functions inside different script tags). Thanks in advance.
-
IAmYourFaja almost 12 yearsWell, foo() is defined inside a page header, and bar() is defined inside the footer. Therefore foo() does appear "higher" (line number wise) in the resultant HTML than bar(). Is it possible that, since these are all defined on page load, that because foo() gets defined first, bar() does not yet exist? In this case, how do I force bar() get defined first (or better yet, that foo() not get called until bar() has already been defined during page load)?!?
-
IAmYourFaja almost 12 yearsI appreciate your input, but the actual HTML is enormous and requires this non-SSCCE to even be askable. Please see my comments underneath @Joseph's answer as I think he is on the right track. Thanks again for all your help so far.
-
IAmYourFaja almost 12 yearsAhhh, it was an ordering issue. I placed bar() in the header above foo()'s definition and all is well. Thanks Joseph!
-
Koen Peters almost 12 yearsI understand. I mentioned his answer in one of the possible solutions in my answer as well. Good to hear that you got it running