1

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?

1 Answer 1

4

You're declaring "foo" with var inside 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.

$(function() {
   $('#btn').data('foo', 'some value');
   $('#btn').click(function() {alert($(this).data('foo'))});
}

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.

4
  • Thanks for the explanation. Yes, I want to avoid making foo global. Unfortunately, your other solution does not really help with my actual problem, in which the function assigned to foo is much more complex than alert(...). Is there any way that I can combine the two anonymous functions in the .ready() while maintaining multiple .ready()? Sep 28, 2012 at 0:17
  • Well there's no way to mechanically combine separate functions after the fact, other than to make them somehow non-anonymous and call them in series from a single function. It's not really clear to me what your larger issue is; perhaps that would be a good topic for a separate question.
    – Pointy
    Sep 28, 2012 at 0:19
  • 2
    Maybe what you could do is extend the jQuery object, similar to the way jQuery plugins do, so you could call it as $.foo(). This only pollutes the jQuery namespace, not the global namespace.
    – Barmar
    Sep 28, 2012 at 0:34
  • @Barmar - Thanks. I started another SO question. Feel free to add your answer to it if you want. here Sep 28, 2012 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.