Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

coffeescript - Curly Braces when Extending Node.js Class

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

For example, Trevor Burnham, in his tutorial on Event-Driven CoffeeScript, extends Node's EventEmitter this way:

{EventEmitter} = require 'events'

class Rooster extends EventEmitter
  constructor: ->
    @on 'wake', -> console.log 'COCKADOODLEDOO!'

(foghorn = new Rooster).emit 'wake' # COCKADOODLEDOO!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...