Reputation: 14183
I read a lot of posts and ask/answer about javascript anonymous self-executing functions, but I'm afraid I'm still missing the point. Why does this code show myvar value? Shouldn't the construct (function(){ code })() keep all variables not visible from outside?
(function(){
myvar = 5;
})();
alert(myvar);
so what's the difference betwen above code and
function myfunction(){
myvar = 5;
};
myfunction();
alert(myvar);
?
Upvotes: 1
Views: 165
Reputation: 11048
Variables are scoped at the function level in javascript. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.
In your case, your myVar is available to the whole window as somebody pointed out already.
If you need to explicitly cage your variable inside a function scope, create an anonymous function and then execute it straight away and all the variables inside will be scoped to the function
(function(){
var myvar = 5;
})();
alert(typeof(myVar));
results "undefined"
Upvotes: 2
Reputation: 35829
myvar
is defined in window scope, hence it is accessible to all.
You should scope myvar
IF you want to keep it private, with var
:
(function(){
var myvar = 5;
})();
Upvotes: 3
Reputation: 413826
You failed to declare "myvar" with var
.
See what happens when you change it like this:
(function(){
"use strict";
myvar = 5;
})();
Upvotes: 2