if-condition 中的对象解构导致全局变量?

Object destructing in if-condition results in global variable?

有人可以向我解释为什么在以下情况下我可以在全局范围内访问 "m":

const a = {m: 'beeb'};


const magic = function topLevel () {
   function lowerLevel() {
    if ({m} = a ) { 
      console.log('in lowerLevel-func: ', m);
    }
  }

  lowerLevel();
}


magic();

console.log('in global', m);

这里是JSFiddle

编辑:澄清一下,我没有在任何地方使用它,我只是想知道它怎么可能。现在我知道了,谢谢!

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. And since you are doing =(Assigning) instead of ==(compairing)

<!DOCTYPE html>
<html>

<body>

  <p>
    If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable:
  </p>

  <p id="demo"></p>

  <script>
    myFunction();

    // code here can use carName as a global variable
    document.getElementById("demo").innerHTML = "I can display " + carName;

    function myFunction() {
      carName = "Volvo";
    }
  </script>

</body>

</html>

References

另读What is the scope of variables in JavaScript?

发生这种情况是因为您从未明确声明(使用 varletconst 语句)m 变量,因此它变成了 属性全局 Window 对象(这就是为什么您可以从代码中的任何位置访问它的原因)。如果您打算在 if 语句中为 m 赋值而不是进行比较,这将是解释。

请注意,如果您在严格模式下执行相同的操作,则不会出现这种行为,因为它不允许使用从未声明过的变量。

您观察到此行为是因为您正在对先前未声明的变量进行赋值 并且您正在 non-strict 模式下执行代码。

行:

if ({m} = a ) { 

实际上是将变量 am 字段赋值给变量 m。现在因为 m 之前没有被声明也不存在于全局范围内,所以可能会发生两件事:

  • 在非严格模式下,这会退化为对 window['m'] 的赋值,这使得它在全球范围内可用
  • 在严格模式下你会得到一个引用错误。

我认为最后一个行为应该是您应该针对的行为,因为它是 (imo) 最少的 "surprising" 行为。