Is it necessary to initialize an object in angular?

0

I have an external class export class as template for an object.

export class Car{
  name: Boolean;
  other: {
    prize: String;
    brand: String;
  };
  doors: {
    number: String,
    size: String,
  };
}

I try to access it from another class, so I created a new variable

var car= new Car();

Since name is a boolean , I assume that it is initialized with a true since it is its default value. My problem comes when I try to initialize the object% of% if it does not have it.

  var car= new Car();
  this.car.doors[pos].number;

When I try to access it, it tells me that doors . How could I access it? I guess I need to initialize it in the constructor.

I do not need to initialize undefined

    
asked by Mario López Batres 16.01.2018 в 13:42
source

1 answer

2

You must initialize it in your constructor if you want to access its attributes, since it is a "Own object" , I leave you an alternative:

 export class Car{
  name: Boolean;
  other: Others;
  doors: Doors;

 constructor(){
    this.name = (true / false); //Segun te parezca correcto.
    this.other = new Other(); // Inicializas el objeto Other - Opcional, ya que no lo necesitas
    this.doors = new Doors(); // Inicializas el objeto Doors
 }
}
// Alternativa a class Car ------------------------------------
export class Car {
  constructor(public name: Boolean = true,
              public doors: Doors = new Doors(), 
              public other: Other = new Other()){}

// Esto te permite tener un constructor al que le podrías pasar parámetros y si no lo haces por defecto utiliza lo que se encuentra a la derecha del =
//--------------------------------------------------------------
export class Doors{
    number: String;
    size: String;
}
export class Other {
    prize: String;
    brand: String;
}
var car= new Car(); // Ya te permitiría ingresar a Doors y Others (si fuese necesario)

The variables within Other and Doors , will be undefined if you try to access them, since no value is assigned to it.

    
answered by 16.01.2018 / 14:03
source