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 when foo()
is getting called. I see a console error in Firebug stating blah()
is not defined. I'm wondering if blah()
only has scope inside its own <script>
tag, and likewise for foo()
. 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.
Script tags are scoped to the app that created them. When an app is uninstalled from a shop, all of the script tags that it created are automatically removed along with it.
js" extension and the <script> tag is an HTML tag, so... Javascript does not recognizes the statement and it will give you an error. However you could have nested <script> tags for example... in single/multiple HTML files.
JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function. They all have Function Scope: function myFunction() {
Up to this point all of the JavaScript Code was in one <SCRIPT> tag, this does not need to be the case. You can have as many <SCRIPT></SCRIPT> tags as you would like in a document.
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:
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With