I have a global var defined in a .js file.:
If my function has an argument with the same name as the global variable, the function can not initialise the global variable:
var myvar;
function init(myvar){
myvar= myvar;
}
But if I change the variable names so the global variable and argument have different names, the function can initialise the global variable:
var myvar2;
function init(myvar){
myvar2= myvar;
}
(myvar2 is then initialised correctly).
Why is this the case ? javascript does not allow two variables with same name in different scope so variable shadowing is occuring ?
I thought the js engine would be be able to distinguish between method scope and global scope in the same way that java does (albeit using the this keyword)
That is correct; the global variable is being shadowed. Think about it. In this statement:
if there was no shadowing, which
myvarwould be the global one and which the local one?