coffeescript syntax {var}?

2019-08-30 14:44发布

问题:

Very simply I am seeing the following syntax using coffeescript in node, that I never saw using coffeescript in the browser.

  {foo} = app.locals.foo

I headed over to js2coffee to see what this does, but it appears to be identical in js output to

  foo = app.locals.foo

So what is going on here? What does the {} syntax mean in this context? Why would you use it?

回答1:

From the fine manual:

Destructuring Assignment

To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left.
[...]
Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties.

The relevant example is this one:

futurists =
  sculptor: "Umberto Boccioni"
  painter:  "Vladimir Burliuk"
  poet:
    name:   "F.T. Marinetti"
    address: [
      "Via Roma 42R"
      "Bellagio, Italy 22021"
    ]

{poet: {name, address: [street, city]}} = futurists

That is short hand for this:

name   = futurists.poet.name
street = futurists.poet.address[0]
city   = futurists.poet.address[1]

and you can see it in action over here.

Basically, the object form of destructured assignment allows you to unpack objects in a somewhat natural way. Perhaps a simpler example would help:

o =
    a: 'b'
    c: 'd'
    e: 'f'

{a, e} = o

That's shorthand for:

a = o.a
e = o.e

And another demo.

You can think of the left hand side of a destructured assignment as a pattern that is used to unpack the right hand side.