UPDATE:
QUESTION SOLVED! I realized that the reason for this is due to ‘hoisting.’ Basically, the JavaScript interpreter parses the code and declares all variables (but does not initialize them) at the beginning of the function. That’s why the second examples isn’t working. Because JavaScript interpreter declares var changed; at the beginning of the function, but does not initialize it until it reaches the body of the code.
For function declaration like the first example, instead of JavaScript moving up just the variable name like the second example, it moves up (or ‘hoists’) up the entire function at the beginning of the parent function, which is why it works!
Anyway, I wrote this for personal reference and thanks for the answers…
This one works: http://jsbin.com/emarat/7/edit
$(function(){
$name = $('#test');
$name.change(changedName);
function changedName (e){
console.log('e: ', e);
console.log('e.currentTarget: ', e.currentTarget);
console.log('$(e.currentTarget).val(): ', $(e.currentTarget).val());
$('#test-display').text($(e.currentTarget).val());
}
});
but this one doesn’t: http://jsbin.com/emarat/9/edit
$(function(){
$name = $('#test');
$name.change(changed);
var changed = function(e){
console.log('e: ', e);
console.log('e.currentTarget: ', e.currentTarget);
console.log('$(e.currentTarget).val(): ', $(e.currentTarget).val());
$('#test-display').text($(e.currentTarget).val());
};
});
Why?
The latter one is equivalent to:
which makes it obvious why it doesn’t work. At the time of usage, the
changedvariable is not yet initialized (undefined).But if you declare a function using the
function yourFunctionName()syntax, it is available in the whole scope. (Which, in JavaScript, is the parent function.) Otherwise it wouldn’t be possible to use functions prior to their declaration. It is called hoisting.See also: