Javascript 分解分配:参数之间相互依赖的顺序

Javascript 分解分配:参数之间相互依赖的顺序,javascript,destructuring,Javascript,Destructuring,我认为在检索到所有参数后会执行解构,但是我注意到这段代码是有效的 函数提取(propertyName,{[propertyName]:value}){ log(propertyName,value); } 提取('property',{property:'value'})参数值是按顺序确定的,就像您将每个参数编写为自己的let声明,从收到的实际参数中获取值一样。(这不是它的实际工作原理,这只是一个类比。) 因此,您的第一个示例在概念上的行为如下: // ONLY CONCEPTUAL func

我认为在检索到所有参数后会执行解构,但是我注意到这段代码是有效的

函数提取(propertyName,{[propertyName]:value}){
log(propertyName,value);
}

提取('property',{property:'value'})参数值是按顺序确定的,就像您将每个参数编写为自己的
let
声明,从收到的实际参数中获取值一样。(这不是它的实际工作原理,这只是一个类比。)

因此,您的第一个示例在概念上的行为如下:

// ONLY CONCEPTUAL
function extract() {
    let propertyName = /*...the first actual argument...*/;
    let { [propertyName]: value } = /* ...the second actual argument... */;
    console.log(propertyName, value);
}
// ONLY CONCEPTUAL
function extract() {
    let { [propertyName]: value } = /* ...the first actual argument... */;
    let propertyName = /*...the second actual argument...*/;
    console.log(propertyName, value);
}
而你的第二个行为是这样的:

// ONLY CONCEPTUAL
function extract() {
    let propertyName = /*...the first actual argument...*/;
    let { [propertyName]: value } = /* ...the second actual argument... */;
    console.log(propertyName, value);
}
// ONLY CONCEPTUAL
function extract() {
    let { [propertyName]: value } = /* ...the first actual argument... */;
    let propertyName = /*...the second actual argument...*/;
    console.log(propertyName, value);
}
…因此,它尝试在初始化“变量”之前使用
propertyName
的值,得到一个错误。(因为参数表达式是在ES2015中添加的,所以对它们使用了
let
而不是
var
语义。)

另一种看待它的方式是,如果您将整个参数列表看作迭代器解构的内容,它的工作方式完全相同。这样想,你的第一个例子是:

//  v−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−v−−−−− iterable destructuring
let [propertyName, { [propertyName]: value }] = /* an iterable for the actual arguments */;
//   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−− parameter list
这在和章节的规范中有所介绍


请注意,这实际上与解构无关,只是在运行函数代码时如何将参数值分配给参数。例如,如果您尝试在早期参数的默认值表达式中使用更晚的参数名称,它将因同样的原因失败。

非常感谢。你知道这是否会改变吗?如果有一个更聪明的行为,首先解决可解析的参数,然后解决其他参数,那将是非常好的。@GuerricP-我没有听说过任何关于更改它的事情,尽管我已经过时几个月了。如果它改变了,我会非常震惊。FWIW,我在我的新书《JavaScript:新玩具》的第7章中对此进行了非常详细的讨论,包括这个概念,你可以将参数列表视为一个可移植的解构模式的内容。如果你感兴趣,请在我的个人资料中添加链接。这不是标准的处理顺序吗,L->R?