Curly Braces when Extending Node.js Class

后端 未结 1 823
醉酒成梦
醉酒成梦 2020-12-08 14:25

Why do we wrap our variables in curly braces, like {EventEmitter} = require \'events\', when extending a Node.js class?

For example, Trevor Burnham, in

相关标签:
1条回答
  • 2020-12-08 15:17

    This:

    {EventEmitter} = require 'events'
    

    is equivalent to this JavaScript:

    var EventEmitter;
    EventEmitter = require('events').EventEmitter;
    

    When you require 'events', you're getting an object back with the module's exports, one of those exports is the EventEmitter "class". Using {EventEmitter} is just an idiomatic shortcut for pulling EventEmitter out of the object that require 'events' returns; you could also say this:

    EventEmitter = require('events').EventEmitter
    

    if you prefer. The braced version starts to come in handy when you want to extract more than one part of an object; for example, this:

    {a, b} = c
    

    is like this JavaScript:

    var a, b;
    a = c.a;
    b = c.b;
    

    The Destructuring Assignment section of the CoffeeScript documentation might make some good reading right about now.

    0 讨论(0)
提交回复
热议问题