I am reading the topics about the execution context and scope of javascript.Below is a simple code:
var scope="global";
function t(){
alert(scope); // alert :"undefined"
var scope="local" ;
alert(scope); // alert: "local"
}
t();
If I remove 'var scope="local" ; ' ,it becomes this:
var scope="global";
function t(){
alert(scope); // alert :"global"
}
t();
I don't understand why the value of scope is changed to "global" in the second case after I remove var scope="local" in the function t().
Could someone help to explain this, thank you!
When you do this:
scope = 'global'
function t() {
alert(scope) // undefined
var scope = 'func'
alert(scope) // func
}
t()
at the line var scope..., you're telling js: watch out, I'm defining 'scope' in this function. So JS resets it's value (undefined). It's like if you did:
scope = 'global'
function t() {
var scope; // erase previous 'scope', so it is now undefined
alert(scope) // undefined
scope = 'func'
alert(scope) // func
}
t()
But if you just do
scope = 'global'
function t() {
alert(scope) // global
}
t()
You're not creating the variable scope in your function, so JS does not erase it's value, and when you try to access it, JS tries to find it higher (in the global namespace in this case)
Hope you get it... It indeed a bit weird, because first, JS looks for every variable you are declaring in you function (and reset/initialise them) and then run your function.
Matt
Essentially, in your first example, the scope of scope (i.e. the var declared inside the function) is the entire body of the function t. It doesn't have a value until it gets to the var scope == ... line, but it is defined from the beginning.
So alert(scope) is resolve "scope" as the locally defined variable, that does not yet have a value - that is, it's undefined.
See this question
The benefits of declaring variables at the top of the function body in JavaScript
for more explanation.
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