【发布时间】:2020-04-06 01:05:36
【问题描述】:
下面是一个简单的 TypeScript 类和它的两个实例。通常,当您创建 Car 类的实例时,您应该能够将您自己的类属性值作为参数传递,就像使用“carName”一样。但是您在构造函数中看到我已经将默认值设置为“maxSpeed”。现在我的两个问题:
- 在“myCar”的实例中,如何告诉它传递构造函数中预定义的“265”的预定义 maxSpeed?像“this.maxSpeed”那样做会给我一个错误,但我没有办法解决它。
- 在“yourCar”的实例中,如何忽略/忽略 maxSpeed 的预定义标准值 265,并传递我自己的值,例如 311,即如下例所示?
我对编程和 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);
【问题讨论】:
标签: typescript class oop parameters constructor