Why did ECMASCRIPT 6 reverse the sides for assignment when destructuring? [closed]

寵の児 提交于 2019-12-29 09:06:52

问题


Why did ES6 decide that left-side assignment made more sense or was more useful for destructured assignments? Just on first look, it seems to make code more error prone, now that assignment can happen on both sides, depending on situation.

let obj = { first: 'Jane', last: 'Doe' };
let { first: f, last: l } = obj;
// f = 'Jane'
// l = 'Doe'

f and l are both seemingly being defined on the left, using values from a combination of the var names on the left and values of those vars from the right.

Given that the rationale for this sytax is the keep it the same as object declaration syntax, why would ECMA not instead have used:

let { f: first, l: last } = obj;

回答1:


Because it is supposed to keep the object literal syntax: the property name comes before the colon. The syntax is supposed to nest, and that wouldn't work properly if the target was on the left side:

let {propName: [arrayElement, ...moreElements], otherName: {nestedProp: targetName}} = obj;

In your approach, it would be

let {[arrayElement, ...moreElements]: propName, {targetName = nestedProp}: otherName} = obj;

where the colon doesn't make any sense.



来源:https://stackoverflow.com/questions/40698433/why-did-ecmascript-6-reverse-the-sides-for-assignment-when-destructuring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!