Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node coffeescript class files and inheritance

I have 2 class files:

foo.coffee: class Foo

bar.coffee: class Bar extends Foo

How do I define these classes so they are globally available? I get the error in Bar that Foo is not defined.

I have an index.js file that I call node on to run the scripts. Here is the contents of index.js, I most likely did this wrong also:

exports.Foo = require("./foo")
exports.Bar = require("/bar")
like image 602
Lee Quarella Avatar asked Feb 27 '12 13:02

Lee Quarella


2 Answers

foo.coffee:

class Foo
  // ...

module.exports = Foo

bar.coffee:

Foo = require "./foo"

class Bar extends Foo
  // ...

module.exports = Bar

index.coffee:

exports.Foo = require "./foo"
exports.Bar = require "./bar"

UPDATE: You also need to run .coffee files with coffee, unless you compile them first.

UPDATE 2: How you structure your models is up to you. I like the pattern above (where simple modules export just a function -- that's when you need to assign to module.exports because you can't simply assign to exports) but others prefer a structure like this:

foo.coffee:

class Foo
  // ...

exports.Foo = Foo

bar.coffee:

Foo = require("./foo").Foo

class Bar extends Foo
  // ...

exports.Bar = Bar

index.coffee:

exports.Foo = require("./foo").Foo
exports.Bar = require("./bar").Bar

Where each module exports an object with one or more properties.

like image 140
Linus Thiel Avatar answered Nov 02 '22 08:11

Linus Thiel


You can also write:

class @MyClass
  [...]

{MyClassName} = require './myclassFile'
myClass = new MyClassName
like image 42
Daniele Vrut Avatar answered Nov 02 '22 07:11

Daniele Vrut