Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain the scope issue I have with this Javascript? [duplicate]

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

I have some Javascript which mostly works except this one function which I can call from some areas but not others. It appears to be a scope issue but I don't know why.

$().ready(function () {
   UpdateElfDisplay(); // <--- Undefined

   $('#Attribute1').change(function () {
      UpdateElfDisplay();  // <--- Works just fine.
   });

   var UpdateElfDisplay = function () {
      // ... some work done here 
   };
 });

As I marked above, the UpdateElfDisplay function works fine when I call it from .change() function but I get an "undefined" if I try to call it when the document is loaded. Can somebody explain why, or direct me to a resource describing this.

like image 875
Sailing Judo Avatar asked Nov 19 '25 06:11

Sailing Judo


1 Answers

You're calling the function before it's defined, so it doesn't work. The one in the handler is invoked later, so it works

If you use a function declaration, it'll be "hoisted" and will work.

function UpdateElfDisplay () {
  // ... some work done here 
}

The JavaScript interpreter evaluates the declaration form of functions before any expressions are evaluated.


Side note

The reason it's a TypeError and not a ReferenceError is that the var UpdateElfDisplay is actually hoisted similar to the function declaration, but the assignment itself is not hoisted.

This means the variable exists, but it doesn't yet have your assigned value.


Side note 2

Your handler could probably be rewritten like this:

$('#Attribute1').change(UpdateElfDisplay);
like image 194
I Hate Lazy Avatar answered Nov 20 '25 19:11

I Hate Lazy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!