简体   繁体   English

节点coffeescript类文件和继承

[英]Node coffeescript class files and inheritance

I have 2 class files: 我有2个类文件:

foo.coffee: class Foo foo.coffee: class Foo

bar.coffee: class Bar extends Foo bar.coffee:class 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. 我在Bar中得到错误,没有定义Foo

I have an index.js file that I call node on to run the scripts. 我有一个index.js文件,我调用node来运行脚本。 Here is the contents of index.js, I most likely did this wrong also: 这是index.js的内容,我也很可能也错了:

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

foo.coffee: foo.coffee:

class Foo
  // ...

module.exports = Foo

bar.coffee: bar.coffee:

Foo = require "./foo"

class Bar extends Foo
  // ...

module.exports = Bar

index.coffee: 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. 更新:你还需要用coffee运行.coffee文件,除非你先编译它们。

UPDATE 2: How you structure your models is up to you. 更新2:您的模型结构取决于您。 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: 我喜欢上面的模式(简单的模块只导出一个函数 - 当你需要分配给module.exports因为你不能简单地分配给exports )但是其他人更喜欢这样的结构:

foo.coffee: foo.coffee:

class Foo
  // ...

exports.Foo = Foo

bar.coffee: bar.coffee:

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

class Bar extends Foo
  // ...

exports.Bar = Bar

index.coffee: index.coffee:

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

Where each module exports an object with one or more properties. 每个模块导出具有一个或多个属性的对象。

You can also write: 你也可以写:

class @MyClass
  [...]

{MyClassName} = require './myclassFile'
myClass = new MyClassName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM