var b = function () {
b = 20;
console.log(b);
};
Object.defineProperty(window, "b", {
writable: false,
configurable: false
});
b();
An anonymous function that is called immediately is most often called an immediately invoked function expression (IIFE). It resembles a function declaration, but because it is enclosed in parentheses it is interpreted as a function expression.
把()中IIFE函数执行过程这样理解试一下:
An anonymous function that is called immediately is most often called an immediately invoked function expression (IIFE). It resembles a function declaration, but because it is enclosed in parentheses it is interpreted as a function expression.
这段话引用自:《javascript高级程序设计第4版》大概意思是立即执行函数,写法上看着像是个“函数声明” 实际上是按“函数表达式”解析的。
回过头来,我们看IIFE为什么要这样设计?
这里的局部变量b(函数体b)我们外部能调用吗?
不能,该变量只能在函数体内部被访问,它代表命名空间函数本身。
我们没有理由去声明一个与命名空间函数名冲突的变量名,也没有理由更改这个变量,很显然这与命名空间的思想冲突,我们应该保持该变量的纯净。
因此,这种“命名空间函数名”被作为常量的设计是合理的,建议使用新的变量名存储自己的变量。
至于具体是如何实现的,懂C的同学可以去扒一下v8的源码,臣妾真的是做不到了。
Note:其中不明白的术语,请自行Google
第 33 题:下面的代码打印什么内容,为什么?