Javascript 继承放置在另一个文件中的子类(CoffeeScript)
如何使用CoffeeScript在不同文件中正确组织子类?下面是代码问题的一个简单示例。Snake运行正常,但在尝试使用Dog类(因为它位于另一个类中)时,会出现以下错误: TypeError:Dog不是构造函数 主文件:.test/Animals.coffeeJavascript 继承放置在另一个文件中的子类(CoffeeScript),javascript,node.js,coffeescript,Javascript,Node.js,Coffeescript,如何使用CoffeeScript在不同文件中正确组织子类?下面是代码问题的一个简单示例。Snake运行正常,但在尝试使用Dog类(因为它位于另一个类中)时,会出现以下错误: TypeError:Dog不是构造函数 主文件:.test/Animals.coffee #expect = require "expect.js" Animal = require "../learning/Animals" Snake = Animal.Snake Dog = require "../learning/D
#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()
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 }
家长班级:。学习/动物。咖啡
#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()
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 }
儿童班:。学习/狗。咖啡
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
您应该保持一致,始终导出对象,并始终将导入的对象分解为您需要的部分
或者,我建议给每个类它自己的文件,以避免混淆