在下面,您将看到一个简单的TypeScript类及其两个实例。通常,当您创建Car类的实例时,应该能够将您自己的class-properties值作为参数传递,例如使用“ carName”。但是您会在构造函数中看到,我已经将默认值设置为“ maxSpeed”。现在我有两个问题:
我是编程和OOP的新手,目前对此知识不多。
class Car {
carName:string;
maxSpeed:number;
constructor(carName:string, maxSpeed:number)
{
this.carName = carName;
this.maxSpeed = 265;
}
}
//How can I pass the predefined constructor-value? What is my mistake?
var myCar = new Car('Tesla X', this.maxSpeed);
//This should print "265":
console.log(myCar.maxSpeed);
//How can I break the rule of the predefined constructor-value and get this 311 printed in the console? It still prints me the 265.
var yourCar = new Car('Tesla X', 311);
//This should print "311":
console.log(yourCar.maxSpeed);
答案 0 :(得分:0)
none
这就是您所需要的:
class Car {
constructor(public carName: string, public maxSpeed: number = 265) {}
}
)const myCar = new Car('Tesla X');
我将class Car {
carName: string;
maxSpeed: number;
constructor(carName: string, maxSpeed: number = 265) {
this.carName = carName;
this.maxSpeed = maxSpeed;
}
}
重命名为carName
。当然,这是汽车名称,因为它是Car类的属性。因此,name
前缀是多余的。
也不要使用car
。使用var
(如果不应该重新分配变量)或const
。
答案 1 :(得分:0)
让我们说说在类/构造函数中maxSpeed变量之后,我添加了第三个变量。然后,将maxSpeed保留为空的解决方案将不再起作用。那么,将所有变量都设置为默认值之后,将所有变量都设置为默认值之后,合法/正确的做法是吗?还是这个变通办法低于合法性?通过使用“未定义”,它仍会按原样记录maxSpeed = 265。
`class Car {
constructor(
public carName: string,
public maxSpeed: number = 265,
public someThing: string
) {}
}
const myCar = new Car('Tesla X', undefined, 'test');
console.log(myCar);`