(function b() {
console.log(b);
b = 20;
console.log(b);
})();
我写了这个 JavaScript IIFE。
第一个
console.log
记录函数体。b
创建 20
变量。console.log
还记录函数体。20
?
因为
b
是常数,无法赋值。您处于非严格模式,因此分配只是默默地执行任何操作,但如果您使用严格模式,您将收到错误,突出显示问题。
(function b() {
'use strict';
console.log(b);
b = 20; // Throws an exception
console.log(b); // Never gets to here
})();
让我们分解一下代码中发生的情况:
(function b() {
console.log(b); // This refers to the function itself
b = 20; // Here you're trying to assign a value to the function, but it won't work as expected
console.log(b); // This still refers to the function itself
})();
b
定义。在函数内部,标识符 b
指的是函数本身。console.log(b)
输出函数定义,因为 b
指的是此时的函数。b = 20;
线。事情变得有趣的地方是:由于 b
被声明为函数本身,因此这一行尝试将值 20
分配给函数 b
。但是,JavaScript 中的函数是对象,您可以为其分配属性,但这不会改变它们作为函数的行为。console.log(b)
仍然引用函数,因此它输出与之前相同的函数定义。本质上,赋值
b = 20
并没有改变b
仍然指的是函数,20
在这个b
里面。