Javascript : 'Variable Not Defined' inside a self invoking function
I wrote the following code that outputs the sum of squared iterating numbers:
(function () {
var i = 4, sum = 0;
while(i--) sum+=i*i;
})();
console.log(sum);
The problem is I get the following error in console: sum is undefined unless I take the sum out and declare it as global scope: //this works but this is not what I want.
sum = 0;
(function ( ) {
var i=4
while(i--) sum+=i*i;
}开发者_开发技巧)();
console.log(sum);
Could some one help me understand? Thanks
var sum = (function ( ) {
var i=4, sum = 0;
while(i--) sum+=i*i;
return sum;
})();
console.log(sum);
You created a local variable called sum
and want to use it outside it's scope. You don't want to declare it in a higher scope so you have to export it.
The only way to export local (primitive) variables is the return
statement.
A self-invoking function has its own scope (i.e. place to live for variables), so sum
ceases to exist after the function and all dependent closures finished executing and it is not accessible from outside. In fact, having a separate scope that won't spoil the global or any other scope is the main reason why People use self executing functions.
Because you are accessing sum
outside your function scope at the line:
console.log(sum)
, where sum is not visible.
If you do not want to put sum
in global scope, then you got to take the statement console.log(sum)
within the function scope.
you are defining sum
inside the function which is local variable. and printing the sum outside the function which is out of scope.
精彩评论