如何使Object.property.property成为一个有效的属性?

Javascript - How do i make Object.property.property a valid property?

本文关键字:property 一个 有效 属性 Object 何使      更新时间:2023-09-26

我目前正在参加一个在线javascript课程,它说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

如果我能得到一些帮助,那就太好了。谢谢!

你几乎是对的。当他们说"also"时,他们的意思是你可以像这样给它们分配一个对象:

this.speed={normal:55,turbo:95};

那么this.speed.normal==55this.speed.turbo==95

可以定义object。property.property只要不是在基本类型的property上定义property