函数参数中的解构赋值到底是如何工作的?

Exactly how do destructuring assigments in function arguments work?

我不明白为什么函数调用中的解构逻辑实际上是在声明一个新变量。

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

console.log(x);

其次,下面的逻辑有什么问题。我得到 Uncaught ReferenceError: x is not defined。但是,当我使用 var 时工作正常。

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

let x = "Dummy";
console.log(x);

我对前面的逻辑知识不足

先回答第二个问题:不能在声明之前使用用let声明的变量(在本例中为x)。在执行 { x } = 时,您会解构为 x.

现在,当您执行 fn({ x } = object) 时,这基本上是一个函数调用,其第一个参数是一个赋值表达式,并且始终计算为右侧的结果。 a=b 计算结果为 b{x} = object 计算结果为 object

I don't understand why the destructuring logic in the call of the function is actually declaring a new variable.

对尚未声明的标识符的任何赋值都会隐式创建一个全局变量。 "use strict" 模式来防止这种情况。

...actually declaring a new variable

这就是我所说的The Horror of Implicit Globals。这一行:

fn({x} = object);

有效:

({x} = object);
fn(object); // a bit of hand-waving here, but roughly speaking...

因为它分配给一个未声明的变量,所以它创建了一个全局变量。如果你使用的是严格模式,你会得到一个 ReferenceError:

"use strict";

function fn() {}
let object = {x: "Ele", y: "From", z: "Stack"};

fn({x} = object);

console.log(x);

赋值的结果是被赋值的值。在解构赋值的情况下,被赋值的值是被解构的东西(object 的值,在你的例子中)。

...secondly, what's the problem in the logic below. I'm getting Uncaught ReferenceError: x is not defined

添加 let x 时出现的问题是分配给 x 的行现在位于 x 声明的时间死区中。 x 此时 保留 ,但未初始化。错误消息显示 "not defined" 因为 let x 行尚未执行。好像你有:

x = 0;
let x;