I'm working on a simple example; I can get it to work with Javascript, but there is something wrong with my CoffeeScript version.
Here is person.coffee:
module.exports = Person
class Person
constructor: (@name) ->
talk: ->
console.log "My name is #{@name}"
And here is index.coffee:
Person = require "./person"
emma = new Person "Emma"
emma.talk()
I am expecting to run index.coffee and see the console output "My name is Emma". Instead, I am getting an error saying TypeError: undefined in not a function.
Put the module.exports
line at the bottom.
----person.coffee----
class Person
constructor: (@name) ->
talk: ->
console.log "My name is #{@name}"
module.exports = Person
coffee> Person = require "./person"
Person = require "./person"
[Function: Person]
coffee> p = new Person "Emma"
p = new Person "Emma"
{ name: 'Emma' }
coffee>
When you assign to module.exports
at the top, the Person
variable is still undefined
.
You could also write in person.coffee
:
class @Person
Then use the following in index.coffee
:
{Person} = require './person'
You could also write
module.exports = class Person
constructor: (@name) ->
console.log "#{@name} is a person"
then in index.coffee
either
bob = new require './person' 'Bob'
or you could do it this way
Person = require './person'
bob = new Person 'bob'
The various answers here seems to take for granted that the only one object exported by the module is the class (kind of "Java way of thinking")
If you need to export several objects (classes, functions, etc), it should probably be best to write:
exports.Person = class Person
[...]
coffee> { Person } = require "./person"
coffee> p = new Person "Emma"