如何在Javascript中定义一个对象,使其主体包含属性,这些属性也是您定义的对象?例如,如果我正在定义一个名为有机体的类 - 并且任何有机体的定义包括另外两种称为生物体A和生物体B的生物体?是这样的:
Organism (){
value: value
Organism organismA; //microbe for example
Organism organismB; //bacteria for example
};
答案 0 :(得分:1)
Javascript不是一种打字语言。
您无法强制执行对象属性的类型。如果你想要那样的话,看看像Typescript这样的东西。
您可以制作“嵌套对象”
var microbe = getMicrobe();
var bacteria = getBacteria();
var organism = { organismA: microbe, organismB: bacteria };
但您无法强制执行其类型:
// not an error (until you try to use the property as an Organism)
organism.organismA = "Not an Organism";
organism.organismB = 123;
organism.doesntEvenExist = microbe;
答案 1 :(得分:1)
如果您正在尝试创建一个构造函数,该构造函数将在实例上定义属性,这些属性也是对象的实例,那是不可能的。 让我们举例说这是你的构造函数:
function Organism(){ this.organismA = new Organism(); }
然后尝试创建一个新实例会导致“RangeError:超出最大调用堆栈大小”,并且有充分理由,因为每次创建新实例时,它都会尝试自己创建一个新实例,因此直到你超过筹码。
但您可以在javascript中执行此操作:
function Organism () {}
var organism = new Organism();
organism.organismA = new Organism();
organism.organismB = new Organism();
// And now the instance and its properties are all Organism
console.log('organism is instance of Organism: ' + (organism instanceof Organism)); // true
console.log('organism.organismA is instance of Organism: ' + (organism.organismA instanceof Organism)); //true
console.log('organism.organismB is instance of Organism: ' + (organism.organismB instanceof Organism)); //true
// If you want you can wrap this in a factory
function createExtendedOrganism () {
var organism = new Organism();
organism.organismA = new Organism();
organism.organismB = new Organism();
return organism;
}
var extendedOrganism = createExtendedOrganism();
// Again the instance and its properties are all Organism
console.log('extendedOrganism is instance of Organism: ' + (extendedOrganism instanceof Organism)); //true
console.log('extendedOrganism.organismA is instance of Organism: ' + (extendedOrganism.organismA instanceof Organism)); //true
console.log('extendedOrganism.organismB is instance of Organism: ' + (extendedOrganism.organismB instanceof Organism)); //true