+function foo(){
foo=10;//我的问题代码
console.log(foo);//方法自己
}();
console.log(typeof foo);//undefined 观察是否全局污染
I would like to ask where the 10 that is reassigned to foo inside the function foo goes, and how the function foo with the same name prevents global pollution. Please solve and expand
The questioner can ask this, that’s fine. However, this problem can be solved through practice. . .
First of all, the questioner has no problem with the way to write IIFE. There are many ways to write IIFE. The most common ones are what @ewind said and:
There are also uncommon ones:
Then let’s talk about the code:
When assigning a value to the current function name in a function:
foo = 10;
Invalid. (I agree with @ewind, it will be ignored here. There should be a more reasonable explanation.) The JS parser will ignore it.The resultI executed in the Chrome console is:
This proves what I said aboveignore.
Then because IIFE simulates block scope, the external environment cannot access internal variables. So it’s undefined.
@ewind said that because foo is an anonymous function, then what?
Obviously the concepts are confused. The foo function is not an anonymous function.
MDN
First of all, the code posted is incomplete. The full version should be like this
This does seem counter-intuitive, because foo declared without a var does not pollute the global scope.
But if the variable name declared in the function is not foo, it is very intuitive, as follows:
So why does a problem occur when the variable declared in the function has the same name as the function name? You can see this example:
After the immediately executed function has the function name foo, the arguments.callee when calling is actually a reference to foo. Comparing the two, we can find that foo is the function object at this time. At this time, the assignment operation will not take effect. When encountering the foo variable without a var declaration, the interpreter will also find this function object, thus preventing pollution in the global scope.