[英]Inheritance of a child class placed in another file (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
您應該保持一致,並始終導出對象,並始終將導入的對象分解為所需的那些部分。
另外,我建議給每個類自己的文件,以免造成混淆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.