javascript - 继承放置在另一个文件中的子类(CoffeeScript)

标签 javascript node.js coffeescript

如何使用 CoffeeScript 在不同文件中正确组织子类?这是代码问题的一个简单示例。 Snake 运行得很好,但是当尝试使用 Dog 类(因为它被放置在另一个类中)时,会出现以下错误:

TypeError: Dog is not a constructor

主文件: .test/Animals.coffee

#expect = require "expect.js"
Animal = require "../learning/Animals"
Snake = Animal.Snake
Dog = require "../learning/Dog"
#Dog = Animal.Dog #unresolved variable

describe 'animals', ->
  it 'test inheritance', ->
    sam = new Snake "Sammy the Python"
    peanut = new Dog "Peanut the Dog"

    sam.move()
    peanut.move()

父类:.learning/Animals.coffee

class Animal
  constructor: (@name) ->

  move: (meters) ->
    console.log(@name + " moved #{meters}m.")

class Snake extends Animal
  move: ->
    console.log( "Slithering...")
    super 5

module.exports = { Animal, Snake }

子类:.learning/Dog.coffee

Animal = require './Animals'

class Dog extends Animal
  move: ->
    console.log( "Runs...")
    super 15

module.exports = { Dog }

最佳答案

您正在导出包含类的对象:

module.exports = { Dog }

这相当于

module.exports = {
  Dog: Dog
}

您可以解构导入的对象:

{ Dog } = require('./Dog.coffee')

这类似于:

a = require('./Dog.coffee')
Dog = a.Dog

您应该保持一致,始终导出对象,并始终将导入的对象解构为您需要的部分。

或者,我建议为每个类提供自己的文件以避免混淆

关于javascript - 继承放置在另一个文件中的子类(CoffeeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55853265/

相关文章:

javascript - 在两个单选按钮之间切换

javascript - 如何使用 typescript 将类变量传递到函数内的函数中?

javascript - 将 ByteArray 从 Knockout.js 发布到 Web 服务

coffeescript - 在生态模板中获取循环索引

javascript - Chrome 扩展通知仅显示一次

javascript - SocketIo - 设置套接字变量不起作用

javascript - Parsehub 选择 Node 语法

node.js - 如何在 sails.js 中的 SocketIO 握手期间修复 'No valid session available from this socket'?

javascript - mousedown 在 sibling 上的传播

coffeescript - 如何用 gulp 编译 bootstrap-sass?