javascript - 继承放置在另一个文件中的子类 (CoffeeScript)
问题描述
如何使用 CoffeeScript 在不同文件中正确组织子类?这是代码问题的简单示例。Snake 运行得很好,但随后尝试使用 Dog 类(因为它被放置在另一个类中),它给出了以下错误:
TypeError: Dog 不是构造函数
主文件: .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 - TypeScript:Ajax 调用总是调用错误而不是成功时成功
- python - 如何返回可修改的别名 python 函数?
- java - 无法在 child() firebase 错误中为参数“pathString”传递 null
- php - 将动态字段数据插入mysql
- java - 在@Component 和@Configuration 中使用@Bean
- vb.net - vb.net 中的 BC36645 错误
- c# - 使用 VSTS Git API C# 获取分支项目
- java - 如何从kafka avro记录生成pojo?
- tendermint - Tendermint Networks,如果某些节点离线,有什么方法可以获取该节点丢失的数据?
- c++ - 在 Visual Studio 中查找包含 iostream 的文件