问题描述
为什么我们在扩展 Node.js 类时将变量包裹在花括号中,例如 {EventEmitter} = require 'events'
?
Why do we wrap our variables in curly braces, like {EventEmitter} = require 'events'
, when extending a Node.js class?
例如,Trevor Burnham 在他的教程中关于事件-Driven CoffeeScript,以这种方式扩展 Node 的 EventEmitter:
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!
推荐答案
这个:
{EventEmitter} = require 'events'
相当于这个JavaScript:
is equivalent to this JavaScript:
var EventEmitter;
EventEmitter = require('events').EventEmitter;
当您require 'events'
时,您将使用模块的导出返回一个对象,其中一个导出是EventEmitter
类".使用 {EventEmitter}
只是将 EventEmitter
从 require 'events'
返回的对象中拉出的惯用快捷方式;你也可以这样说:
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
就像这样的JavaScript:
is like this JavaScript:
var a, b;
a = c.a;
b = c.b;
CoffeeScript 文档的 解构赋值 部分现在可能会成为一些不错的读物.
The Destructuring Assignment section of the CoffeeScript documentation might make some good reading right about now.
这篇关于扩展 Node.js 类时的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!