I found the following two examples of setTime function, although the code looks the same, the result is different in the two cases.
Example1: Result "Hello Stack Overflow"
var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";
Example2: Result "Hello world"
function callback(a){
return function(){
alert("Hello " + a);
}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";
Why in the first example the value of a changed, and in excample2 it didn't?
In the first example, the function reads the value of a directly. In the second example, the function reads the value of the parameter passed to it's factory function. Even though we reassign the value of the variable later, that doesn't affect the value of the parameter. It might be more clear if a different name is used for the parameter:
function callback(x){
return function(){
alert("Hello " + x);
}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";
If you had used an object, you'd have a different story. Modifying your examples slightly, these both have the same result:
Example 1
var o = {};
o.a = "world";
setTimeout(function(){alert("Hello " + o.a)}, 2000);
o.a = "Stack Overflow";
Example 2
function callback(obj){
return function(){
alert("Hello " + obj.a);
}
}
var o = {};
o.a = "world";
setTimeout(callback(o), 2000);
o.a = "Stack Overflow";
It doesn't change in the second example because you are actually creating a new local variable a as the argument to the callback function. So when you change the value of the global a it doesn't effect the value of the a inside that function.
a points at the string "world"a gets passed to functiona is created and set to the value of global var aa is set to a new valueaSo because function arguments have the semantics of local variables, you can't change it after the fact like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With