为什么第二个console.log输出是函数体而不是20?

问题描述 投票:0回答:2
(function b() {
  console.log(b);
  b = 20;
  console.log(b);
})();

我写了这个 JavaScript IIFE。
第一个

console.log
记录函数体。
然后使用值
b
创建
20
变量。
第二个
console.log
还记录函数体。
为什么不
20

javascript iife
2个回答
4
投票

因为

b
是常数,无法赋值。您处于非严格模式,因此分配只是默默地执行任何操作,但如果您使用严格模式,您将收到错误,突出显示问题。

(function b() {
  'use strict';
  console.log(b);
  b = 20;         // Throws an exception
  console.log(b); // Never gets to here
})();


1
投票

让我们分解一下代码中发生的情况:

(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
})();
  1. IIFE(立即调用函数表达式)用名称
    b
    定义。在函数内部,标识符
    b
    指的是函数本身。
  2. 第一个
    console.log(b)
    输出函数定义,因为
    b
    指的是此时的函数。
  3. 遇到
    b = 20;
    线。事情变得有趣的地方是:由于
    b
    被声明为函数本身,因此这一行尝试将值
    20
    分配给函数
    b
    。但是,JavaScript 中的函数是对象,您可以为其分配属性,但这不会改变它们作为函数的行为。
  4. 第二个
    console.log(b)
    仍然引用函数,因此它输出与之前相同的函数定义。

本质上,赋值

b = 20
并没有改变
b
仍然指的是函数,
20
在这个
b
里面。

© www.soinside.com 2019 - 2024. All rights reserved.