Node.js + Coffeescript类具有多个导出的继承?

时间:2013-12-04 00:33:05

标签: javascript node.js inheritance coffeescript

在Node.js和Coffeescript中,我定义了一个类Connector,它继承自Node的EventEmitter

我想定义Connector的子类,名为Foo。当我尝试定义Foo的新实例时,我会收到:TypeError: Cannot read property 'prototype' of undefined

我认为这是因为我没有在我的Connector中导出module.exports类,但我如何导出_.tap()函数,以及Connector其他类可以作为要扩展的父类使用吗?

# connectors.coffee
{ EventEmitter } = require 'events'
FS               = require 'fs'
Q                = require 'q'
_                = require 'underscore'
logger           = require './logger'

class Connector extends EventEmitter
  constructor: (@credential) ->

  name : 'Unnamed Connector'
  group: undefined

  search: (query) ->
    @_search(query)
    this

  _results: (results) ->
    @emit 'results', results

  _end: ->
    @emit 'end'

  _error: (error) ->
    @emit 'error', error

  module.exports = _.tap {}, (connectors) ->
    FS.readdirSync("#{__dirname}/connectors").forEach (file) ->
      # some logic


# foo.coffee
Connector = require '../connectors'
logger    = require '../logger'

class Foo extends Connector
  constructor: ->

  name: "test_connector"

  _search: (query) ->
    logger.info "Foo connector queried: #{query}"
    logger.info "Returning fake results, stand by"

module.exports = Foo

1 个答案:

答案 0 :(得分:1)

那可以这样做(顺序很重要):

module.exports = _.tap {}, (connectors) ->
  #
  # your logic here
  #

module.exports.Connector = Connector

#i_use_tap.coffee
tapFunctionResult = require('../connectors')

#foo.coffee
Connector = require('../connectors').Connector
class Foo extends Connector