简体   繁体   English

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

[英]Inheritance of a child class placed in another file (CoffeeScript)

How to organize properly child classes in different files with CoffeeScript? 如何使用CoffeeScript在不同文件中正确组织子类? Here is a simple example of the problems with the code. 这是代码问题的简单示例。 The Snake runs just fine, but then trying to use the Dog class (because it is placed in another class), it gives the following error: Snake运行得很好,但是随后尝试使用Dog类(因为将其放置在另一个类中),则产生以下错误:

TypeError: Dog is not a constructor TypeError:Dog不是构造函数

Main file: .test/Animals.coffee 主文件: .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()

Parent class: .learning/Animals.coffee 父班: .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 }

Child class: .learning/Dog.coffee 子班: .learning / Dog.coffee

Animal = require './Animals'

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

module.exports = { Dog }

You are exporting objects containing classes: 您正在导出包含类的对象:

module.exports = { Dog }

This is equivalent to 这相当于

module.exports = {
  Dog: Dog
}

You can destructure the imported object: 您可以解构导入的对象:

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

This is similar to: 这类似于:

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

You should be consistent and always export objects, and always destructure the imported object into those parts which you need. 您应该保持一致,并始终导出对象,并始终将导入的对象分解为所需的那些部分。

Alternatively, I would suggest giving each class it's own file to avoid confusion 另外,我建议给每个类自己的文件,以免造成混淆

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

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