我目前正在参加在线 javascript 类(class),它说 Object.property.property 是一个有效的变量,但我一生都无法在互联网上找到有关它的任何内容或使其在我的程序中工作。在本节的注释中,它说可以使对象的属性具有子属性。以下是该示例引用的代码:
function car () {
this.weight=0;
this.engine="";
this.aero_factor=0;
this.speed=0;
}
var porsche = new car()
它在说“属性也可以是对象”时给出的例子是:
car.interiorStyle=”Type 12”;
car.interiorStyle.upholstery=”Leather”;
car.interiorStyle.airConditioning=true;
car.interiorStyle.radio=”JVC”;
car.interiorStyle.radio.power=200;
但就是这样。它根本没有说明如何实现它,我也不明白为什么当我这样做时,它每次都会以未定义的形式结束。
这是我的代码:
function Car(weight, speed, turboSpeed) {
this.weight=weight;
this.speed=speed;
this.speed.turbo = turboSpeed;
}
var porsche = new Car(1750, 125, 250);
alert(porsche.weight); //1750
alert(porsche.speed); //125
alert(porsche.speed.turbo); //undefined
如果我能得到一些帮助,那就太好了。谢谢!
最佳答案
你几乎是对的。当他们说“也”时,他们的意思是你可以像这样给他们分配一个对象:
this.speed={normal:55,turbo:95};
那么this.speed.normal==55
,以及this.speed.turbo==95
关于Javascript - 如何使 Object.property.property 成为有效属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715348/