Say that I have a HTML that links to two scripts:
...
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript" src="specific.js"></script>
...
Each of the two scripts has it’s own jQuery’s .ready() defined.
general.js:
jQuery(function() {
var foo;
$('#btn').click(function() {alert(foo())});
}
specific.js:
jQuery(function() {
foo = function() {alert("hello")};
$('#btn').click(function() {foo()});
}
where #btn is a button element.
When I clicked on #btn I was expecting to see “hello” dialog, but instead, I got Uncaught TypeError: undefined is not a function in chrome developer tools.
My own understanding is that foo should have been assigned the function already, instead of being undefined, before it’s accessed by the click event. Obviously, my understanding is incorrect. Can someone please explain to me why it’s behaving the way it is?
You’re declaring “foo” with
varinside the first function. It’s therefore local to that function and not visible external to it.You could make “foo” global by declaring it outside the first “ready” handler.
Global variables are kind-of undesirable; it might be nicer to keep the value as a “data” value on the element itself.
That way the data is associated with the elements (though not directly on the DOM objects; jQuery keeps track of the values in an internal map to avoid DOM-related memory leaks) and you don’t pollute the global namespace.