Different ways of writing a function bringing undesired effects in JavaScript?
-
21-04-2021 - |
Question
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?
La solution
The latter one is equivalent to:
$(function(){
var changed;
$name = $('#test');
$name.change(changed);
changed = function(e){
//...
};
});
which makes it obvious why it doesn't work. At the time of usage, the changed
variable 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:
Autres conseils
Because the variable is defined after its use.
var a = 1;
var c = a + b;
var b = 2;
You wouldn't expect that code to run.
The first one defines a function in the scope. The second one creates a inline function and stores a reference to it in the local variable changed
. The problem is that you fill the variable after you use it.
This would work:
$(function(){
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());
};
$name = $('#test');
$name.change(changed);
});