Typescript 实例化时忽略类的默认值
下面是一个简单的TypeScript类和它的两个实例化。通常,在创建Car类的实例时,应该能够将类属性的值作为参数传递,就像“carName”一样。但是你可以看到,在构造函数中,我已经将默认值设置为“maxSpeed”。现在我有两个问题:Typescript 实例化时忽略类的默认值,typescript,class,oop,parameters,constructor,Typescript,Class,Oop,Parameters,Constructor,下面是一个简单的TypeScript类和它的两个实例化。通常,在创建Car类的实例时,应该能够将类属性的值作为参数传递,就像“carName”一样。但是你可以看到,在构造函数中,我已经将默认值设置为“maxSpeed”。现在我有两个问题: 在“myCar”的实例中,我如何告诉它通过构造函数中预定义的maxSpeed“265”?像“this.maxSpeed”这样做会给我一个错误,但我没有办法绕过它 在“yourCar”的例子中,我如何可以省略/忽略maxSpeed 265的预定义标准值,并传递我
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);
这就是您所需要的:
- 参数可以定义默认值,允许在调用构造函数/函数时忽略它们(maxSpeed可以做到这一点,因此您可以只执行
)const myCar=new Car('Tesla X');
- 如果构造函数参数也是类的属性,则可以在构造函数参数之前使用可见性修饰符声明它。因此,上面是
carName
重命名为name
。当然,这是一个汽车名称,因为它是汽车类的一个属性。因此,car
前缀是多余的
此外,永远不要使用
var
。使用const
(如果不应重新分配变量)或let
假设在类/构造函数中,在maxSpeed变量后添加第三个变量。那么,将maxSpeed留空的解决方案将不再有效。那么,合法/正确的方法是,将所有带有默认值的变量放在所有没有默认值的变量之后吗?还是这项工作不合法?通过使用“undefined”,它仍然会记录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);`
谢谢你,你的两个解决方案都很好!谢谢你的命名提示!你能告诉我为什么会有这样一种情况,构造函数参数不是类的属性吗?(我对OOP和编程基本上是新手)。我真的很想总是像你在答案的前三行那样写这门课,而不是像我在顶部的问题中那样。但是为什么它不能总是用你曾经用过的那种简洁的方式来写呢?你总是可以用简洁的方式。只是不要将public、protected或private放在构造函数参数之前,它只是:构造函数参数,而不是属性?你为什么要那样?当您只需要一个参数在构造函数中处理它时。一个简单的例子:
constructor(name:string){this.name=(name | | |'anonymous').toUpperCase()}
@jb nizet您认为这种使用未定义的方法合法吗?或者我应该将所有具有默认值的变量始终放在类/构造函数的末尾吗?
class Car {
carName: string;
maxSpeed: number;
constructor(carName: string, maxSpeed: number = 265) {
this.carName = carName;
this.maxSpeed = maxSpeed;
}
}
`class Car {
constructor(
public carName: string,
public maxSpeed: number = 265,
public someThing: string
) {}
}
const myCar = new Car('Tesla X', undefined, 'test');
console.log(myCar);`