CoffeeScript中的Node.js模块

我正在做一个简单的例子。 我可以让它与Javascript一起工作,但是我的CoffeeScript版本有问题。

这是person.coffee:

module.exports = Person class Person constructor: (@name) -> talk: -> console.log "My name is #{@name}" 

这里是index.coffee:

 Person = require "./person" emma = new Person "Emma" emma.talk() 

我期望运行index.coffee并看到控制台输出“我的名字是艾玛”。 相反,我得到一个错误,说TypeError:undefined不是一个函数。

module.exports行放在底部。

—- —- person.coffee

 class Person constructor: (@name) -> talk: -> console.log "My name is #{@name}" module.exports = Person 

 Person = require "./person" // [Function: Person] p = new Person "Emma" // { name: 'Emma' } 

当你分配给顶部的module.exports时, Personvariables仍然是undefined

你也可以写person.coffee

 class @Person 

然后在index.coffee使用以下index.coffee

 {Person} = require './person' 

你也可以写

 module.exports = class Person constructor: (@name) -> console.log "#{@name} is a person" 

然后在index.coffee

 bob = new require './person' 'Bob' 

或者你可以这样做

 Person = require './person' bob = new Person 'bob' 

这里的各种答案似乎理所当然地认为模块导出的唯一一个对象是类(“Java思维方式”)

如果你需要导出几个对象(类,函数等),最好写一下:

 exports.Person = class Person [...] 

 coffee> { Person } = require "./person" coffee> p = new Person "Emma"