object destructuring without var

前端 未结 3 1767
自闭症患者
自闭症患者 2020-11-22 07:30

Why does object destructuring throw an error if there is no var keyword in front of it?

{a, b} = {a: 1, b: 2};

throws Sy

3条回答
  •  孤城傲影
    2020-11-22 07:37

    Here's another way:

    let {} = {a, b} = objectReturningFunction()
    

    Pros:

    • No parenthesis needed
    • No semicolons needed
    • The extra assignment is a guaranteed no-op (given that no weird things are going on)

    Cons:

    • Looks a bit weird, although in my opinion no weirder than the !(){...}() IIFE.
    • Might be confusing as to why it's there. It is guaranteed to throw people off on the first encounter, so I would advise against using it as a one-off.

提交回复
热议问题