I'm used to being able to in Java define an object which can contain other objects as members, for example (psuedocode):
我习惯于在Java中定义一个可以包含其他对象作为成员的对象,例如(psuedocode):
class Zoo{
private List<Animal> animals;
}
class Animal {
private double weight;
private double height;
private double species;
}
Then you could have a constructor for zoo which takes X animals and adds them to an animal collection and have it's own methods.
然后你可以有一个动物园的构造函数,它接受X动物并将它们添加到动物集合中并拥有它自己的方法。
In coffeescript I can't seem to be able to do this, is this a limitation of javascript?
在coffeescript中我似乎无法做到这一点,这是javascript的限制吗?
1 个解决方案
#1
hope I understood your question.
希望我理解你的问题。
in Coffeescript you may write
在Coffeescript你可以写
class Animal
name: ''
class Zoo
animals: [] #notice you do not specify type!
constructor: (animalList) ->
@animals = animalList #and animal list is an array of Animal class instances
zoo = new Zoo([new Animal()])
console.log(zoo.animals.length) #should be eq to 1
If you want animals to be private same as it would be in Java or C#, I would recommend not using classes but:
如果你想让动物与Java或C#中的动物相同,我建议不要使用类,但是:
Zoo = (animals) ->
return {
getAnimals: -> animals
addToAnimals: (animal) -> animals.push(animal)
}
#1
hope I understood your question.
希望我理解你的问题。
in Coffeescript you may write
在Coffeescript你可以写
class Animal
name: ''
class Zoo
animals: [] #notice you do not specify type!
constructor: (animalList) ->
@animals = animalList #and animal list is an array of Animal class instances
zoo = new Zoo([new Animal()])
console.log(zoo.animals.length) #should be eq to 1
If you want animals to be private same as it would be in Java or C#, I would recommend not using classes but:
如果你想让动物与Java或C#中的动物相同,我建议不要使用类,但是:
Zoo = (animals) ->
return {
getAnimals: -> animals
addToAnimals: (animal) -> animals.push(animal)
}