Advertisement
Re_21

Typescript POO Herency IMPORTANT

Oct 14th, 2022
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Car {
  2.     // Properties
  3.     // Se crean las propiedades
  4.     /*_make: string;
  5.     _color: string;
  6.     _doors: number;*/
  7.  
  8. private _make: string;
  9. private _color: string;
  10. private _doors: number;
  11. private static numberOfCars: number = 0;  // New static property
  12. // ...
  13.     // Constructor
  14.     // Inicializamos nuestras propiedades
  15.     constructor(make:string, color:string, doors = 4){
  16.         // a traves del this le decimos que vamos a acceder a nuestra propiedad a traves de una variable
  17.         this._make = make;
  18.         this._color = color;
  19.         this._doors = doors;
  20.         Car.numberOfCars++; // Increments the value of the static property
  21.  
  22.         //agregamos una validacion para cuando se pase un parametro a un objeto hijo y se puede validar directamente
  23.         /*if ((doors % 2) === 0) {
  24.         this._doors = doors;
  25.     } else {
  26.         throw new Error('Doors must be an even number');
  27.     }*/
  28. }
  29.     // Accessors
  30.     // a traves de typescript podemos decir si queremos acceder desde la clase public a nuestras propiedadaes en este caso si se puede
  31.     // hacer pero de esta manera le decimos que queremos acceder a traves de una funcion y que nos lo devuelva
  32.     get make(){
  33.         return this._make;
  34.     }
  35.     get color(){
  36.         return 'El color del carro es: ' + this._color;
  37.     }
  38.     get doors(){
  39.         return this._doors;
  40.     }
  41.     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  42.     // aca le decimos que setee o que coloque nuestro make en la variable make del objeto
  43.     set make(make){
  44.         this._make = make;
  45.     }
  46.     set color(color){
  47.         this._color = color;
  48.     }
  49.     set doors(doors) {
  50.     if ((doors % 2) === 0) {
  51.         this._doors = doors;
  52.     } else {
  53.         throw new Error('Doors must be an even number');
  54.     }
  55. }
  56.  
  57.     // Methods
  58.     // en los metodos de una funcion en typescript no usamos la palabra function en metodos
  59.     // Methods
  60. accelerate(speed: number): string {
  61.     return `${this.worker()} is accelerating to ${speed} MPH.`
  62. }
  63. brake(): string {
  64.     return `${this.worker()} is braking with the standard braking system.`
  65. }
  66. turn(direction: 'left' | 'right'): string {
  67.     return `${this.worker()} is turning ${direction}`;
  68. }
  69. // This function performs work for the other method functions
  70. /*worker(): string {
  71.     return this._make;
  72. }*/
  73. protected worker(): string { // <- cambiamos private por protected para que pueda ser accesible en sub clases de car
  74.     return this._make;
  75. }
  76. public static getNumberOfCars(): number {
  77.     return Car.numberOfCars;
  78. }
  79.  
  80. }
  81. // creando un nuevo objeto a partir de otro
  82. let myCar1 = new Car('Cool Car Company', 'blue', 2);  // Instantiates the Car object with all parameters
  83. //console.log(myCar1.color);//parametro que pasa al constructor
  84. //console.log(myCar1._color);//propiedad definida en la clase
  85.  
  86. let myCar2 = new Car('Galaxy Motors', 'red', 2);
  87. //console.log(myCar2.doors)//no genera ningun error por que no se evalua en el Constructor
  88. //myCar2.doors = 5;
  89. //console.log(myCar2)//aca si genera el error
  90.  
  91. let myCar3 = new Car('Galaxy Motors', 'gray');
  92. //console.log(myCar3.doors);  // returns 4, the default value
  93.  
  94. //console.log(Car.getNumberOfCars());    <- Contador de carros que se han creado
  95.  
  96. //volviendolos privados
  97. // Properties
  98.  
  99. //-_-_-_-_-_-_-_-_EXTENDIENDO CAR -_-_-_-_-_-_-_-_-_-_-_-_-_-_
  100. //usando herencia
  101. class ElectricCar extends Car {
  102.     // Properties unique to ElectricCar
  103.     private _range: number;
  104.     // Constructor
  105.     constructor(make: string, color: string, range:number, doors = 2){
  106.         super(make,color,doors); //sirve para usar las propiedades de el objeto original
  107.         this._range = range;
  108.     }
  109.  
  110.     // Accessors
  111. get range() {
  112.     return this._range;
  113. }
  114. set range(range) {
  115.     this._range = range;
  116. }
  117.     // Methods
  118. charge() {
  119.     console.log(this.worker() + " is charging.")
  120. }
  121. // Overrides the brake method of the Car class
  122. brake(): string {
  123.     return `${this.worker()}  is braking with the regenerative braking system.`
  124. }
  125. }
  126. let spark = new ElectricCar('Spark Motors','silver', 124, 2);
  127. let eCar = new ElectricCar('Electric Car Co.', 'black', 263);
  128. /*console.log(eCar.doors);         // returns the default, 2
  129. spark.charge();                  // returns "Spark Motors is charging"
  130. console.log(spark.brake());  // returns "Spark Motors is braking with the regenerative braking system"*/
  131.  
  132. //para ver si el objeto cumple con las validaciones usamos interface agregado de implement
  133. interface Vehicle {
  134.     make: string;
  135.     color: string;
  136.     doors: number;
  137.     accelerate(speed: number): string;
  138.     brake(): string;
  139.     turn(direction: 'left' | 'right'): string;
  140. }
  141. // de esta manera:
  142. /*class Car implements Vehicle {
  143.     // ...
  144. }*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement