Oop Coffeescript对象作为私有成员,是否可能?
我习惯于在Java中定义一个可以包含其他对象作为成员的对象,例如(psuedocode):Oop Coffeescript对象作为私有成员,是否可能?,oop,coffeescript,Oop,Coffeescript,我习惯于在Java中定义一个可以包含其他对象作为成员的对象,例如(psuedocode): class动物园{ 私人动物名录; } 类动物{ 私人双倍重量; 私人双高; 私有双种; } 然后你可以有一个动物园的构造器,它接受X个动物并将它们添加到动物集合中,并有自己的方法 在coffeescript中,我似乎无法做到这一点,这是javascript的限制吗?希望我理解你的问题 用咖啡脚本你可以写 class Animal name: '' class Zoo animals: []
class动物园{
私人动物名录;
}
类动物{
私人双倍重量;
私人双高;
私有双种;
}
然后你可以有一个动物园的构造器,它接受X个动物并将它们添加到动物集合中,并有自己的方法
在coffeescript中,我似乎无法做到这一点,这是javascript的限制吗?希望我理解你的问题 用咖啡脚本你可以写
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
如果您希望动物像在Java或C#中一样是私有的,我建议不要使用类,而是:
Zoo = (animals) ->
return {
getAnimals: -> animals
addToAnimals: (animal) -> animals.push(animal)
}
JavaScript中没有私有属性,扩展到CoffeeScript。只是找到了关于私有成员的信息,这里有点有用,您还可以使其更加隐式:
class Zoo构造函数:(@animals)->
@welldan97是的,我知道,但Craig Harley似乎不知道一般概念,所以我希望尽可能显式
Zoo = (animals) ->
return {
getAnimals: -> animals
addToAnimals: (animal) -> animals.push(animal)
}