实例化时忽略类的默认值

时间:2019-12-12 15:30:26

标签: typescript class oop parameters constructor

在下面,您将看到一个简单的TypeScript类及其两个实例。通常,当您创建Car类的实例时,应该能够将您自己的class-properties值作为参数传递,例如使用“ carName”。但是您会在构造函数中看到,我已经将默认值设置为“ maxSpeed”。现在我有两个问题:

  1. 在“ myCar”的实例中,如何告诉它传递在构造函数中预定义的“ 265”预定义的maxSpeed?像“ this.maxSpeed”那样操作会给我一个错误,但我没有办法解决。
  2. 在“ yourCar”的实例中,如何忽略/忽略maxSpeed的预定义标准值265,并传递自己的值,例如311,如示例belog所示?

我是编程和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);

2 个答案:

答案 0 :(得分:0)

none

这就是您所需要的:

  • 参数可以定义默认值,从而可以在调用构造函数/函数时将其忽略(maxSpeed会这样做,因此您只需执行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);`