Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Clases

24/32
Recursos

Aportes 21

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

Definitivamente amo TypeScript

Podemos hacer console.log del objeto
También podemos hacer console.table de ese mismo objeto
Y como tenemos un array en el objeto, podemos hacer también console.table de ese array dentro del objeto.

Para la clase de Album inicializa el arreglo pictures en el constructor .
Me surgió la pregunta de: ¿Cuál seria la diferencia entre inicializar una variable en el constructor…

class Album {
  pictures: Picture[]
  constructor() {
    this.pictures = []
  }
}

… o inicializarla en la definición de la variable?

class Album {
  pictures: Picture[] = []
  constructor() {
  }
}

¿Sera alguna cuestión de rendimiento, funcionalidad o es por buena práctica?

MY NOTES FOR CLASES

Definiendo Clases y Constructores

A partir de ECMAScript 2015 es posible construir clases y hacer uso del paradigma de la Programación Orientada a Objetos en Javascript

Typescript permite aplicar estas técnicas sin tener que es esperar por otra versión.

export{}

enum PhotoOrientation {

  Landscape,
  Portrait,
  Square,
  Panorama
}

class Picture {

  //Propiedades
  id:number;
  title:string;
  orientation:PhotoOrientation;

  constructor(id:number,title:string,orientation:PhotoOrientation){

    this.id = id;
    this.title = title;
    this.orientation = orientation;

  }

  //Comportamiento de nuestra clase que estara definido por funciones

  toString(){
    return `[id ${this.id},
            title: ${this.title},
            orientation: ${this.orientation}]`;
  }

}

class Album{

  id:number;
  title:string;
  pictures: Picture[];

  //Usamos el constructor el cual nos permitira crear objetos de esta clase
  constructor(id:number, title:string){

    this.id = id;
    this.title = title;
    this.pictures = [];
  }
    addPicture(picture:Picture){
      this.pictures.push(picture);

    }

  }

  //Creamos un nuevo a partir de la instancia de la clase

  const album:Album = new Album(1, 'personal pictures');
  const picture: Picture = new Picture(1, 'Platzi session', PhotoOrientation)
  album.addPicture(picture);

  console.log(album);
export {};
console.clear();

enum PhotoOrientation {
  Landscape = 'Landscape',
  Portrait = 'Portrait',
  Square = 'Square',
  Panorama = 'Panorama',
}

// interface Entity {
//   id: number;
//   title: string;
// }

// class Entity {
//     id: number;
//     title: string;
//   }

class Picture {
  id: number;
  title: string;
  orientation: PhotoOrientation;

  constructor(id: number, title: string, orientation: PhotoOrientation) {
    this.id = id;
    this.title = title;
    this.orientation = orientation;
  }

  // Comportamiento
  toString() {
    return `[id: ${this.id}, title: ${this.title}, orientation: ${this.orientation}]`;
  }
}

class Album {
  id: number;
  title: string;
  pictures: Picture[] = [];

  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
    // this.pictures = [];
  }

  addPicture(picture: Picture) {
    this.pictures.push(picture);
  }
}

const picture: Picture = new Picture(100, 'cool', PhotoOrientation.Square);
const picture1 = new Picture(201, 'korn', PhotoOrientation.Square);
const album: Album = new Album(534, 'Family');
console.log(picture);
console.log(picture1);
album.addPicture(picture);
album.addPicture(picture1);

console.log('album',album);

El ejemplo del profesor un llevado un poco más allá:

enum Orientation {
    Landscape,
    Portrait,
    Square,
    Panoramic
}

class Album {
    readonly id: number;
    title : string;
    pictures : Picture[];

    constructor(id: number, title: string) {
        this.id = id;
        this.title = title
        this.pictures = []
    }

    toString () : string{
        return `Id: ${this.id}\nTitle: ${this.title}`;
    }

    addPicture (picture : Picture) {
        this.pictures.push(picture);
    }
}

class Picture extends Album {
    
    albumId : number;
    orientation : Orientation;
    
    constructor (id: number, title: string, albumId : number, orientation : Orientation) {
        
        super(id, title);

        this.albumId = albumId;
        this.orientation = orientation;
    }

    toString () : string{
        return `Id: ${this.id}\nTitle: ${this.title}\nAlbum: ${this.albumId}\nOrientation: ${this.orientation}`;
    }
}

const birthDay = new Album (3, "Birthday");
const newPic = new Picture (4, "Cake", 3, Orientation.Square);

birthDay.addPicture(newPic);

console.log(birthDay.toString());
console.log("");
console.log(birthDay.pictures[0].toString());
  • Las clases y a la POO, se puede conectar las diferentes entidades y se puede relacionar
  • Una clase es la asbtracción de un conjunto de objetos
    ejemplo:
    Para definir una entidad usuario, se hace uso de una clase: Se debe definir una clase que
    dentro tenga una función que permita crear objetos a partir de esta Clase y poder interactuar con ellos.
export {}

enum PhotoOrientation {
    Landscape,
    Portrait,
    Square,
    Panorama,
};

class Picture {
    // properties
    id: number;
    title: string;
    orientation: PhotoOrientation;
    //constructor
    constructor( id: number, title: string, orientation: PhotoOrientation ) {
        this.id = id;
        this.title = title;
        this.orientation = orientation;
    }
    //Performance
    toString() {
        return `[id: ${this.id}, title: ${this.title}, orientation: ${this.orientation}]`
    }
}

class Album {
    id: string;
    title: string;
    pictures: Picture[];

    constructor( id: string, title: string ) {
        this.id = id;
        this.title = title;
        this.pictures = [];
    }    

    addPicture(picture: Picture) {
        this.pictures.push(picture);
    }
}

let album: Album = new Album('stories-1', 'Photos of mine');
const newPic: Picture = new Picture(2, 'my new pic!', PhotoOrientation.Panorama);
const new2Pic: Picture = new Picture(3, 'my 2nd new pic!', PhotoOrientation.Portrait);
const new3Pic: Picture = new Picture(4, 'my 3rd new pic!', PhotoOrientation.Portrait);
album.addPicture(newPic);
album.addPicture(new2Pic);
album.addPicture(new3Pic);
console.log('album -> ', album);

Tipea las clases User, Album, Picture. La única diferencia con javascript es que usa tipos en los args.

Me encanta lo parecido que tiene a Java 😍

tengo una pregunta referente al ejemplo del álbum. el profesor definió el tipo de type de las variables antes de la funcion. Es necesario definir el type en los parámetro () ya estando definido antes. no se debería haberse guardado la referencia antes.

No sé si han sido curiosos, pero nos estamos ahorrando mucho código en JS con el poder de TS, solamente comparen:
Código en TS:

export {}

enum PhotoOrientation{
  Landscape,
  Portrait,
  Square,
  Panorama
}

class Picture {
  //* Propiedades
  id: number
  title: string
  orientation: PhotoOrientation

  //*Atributos que se consideran necesarios para construir objetos
  constructor(id: number, title: string, orientation: PhotoOrientation) {
    this.id = id
    this.title = title
    this.orientation = orientation
  }

  //*Comportamiento
  toString() {
    return `
    [
      id: ${this.id},
      title: ${this.title},
      orientation: ${this.orientation}
    ]
    `
  }
}

class Album {
  id: number
  title: string
  pictures: Picture[]

  constructor(id: number, title: string) {
    this.id = id
    this.title = title
    this.pictures = [] //*Inicializamos el array vacío
  }

  addPicture(picture: Picture) {
    this.pictures.push(picture)
  }
}

const album: Album = new Album(1, 'Personal Pictures')
const picture: Picture = new Picture(1, 'Selfie', PhotoOrientation.Square)
album.addPicture(picture)

//console.table(album)
//console.table(picture)
//console.table({picture})
console.log(album) //* Imprime el objeto
console.table({album}) //* Como manejamos un objeto, podemos usar console.table
console.table(album.pictures) //* Como tenemos un array dentro del objeto, también podemos usar console.table

Código en JS:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PhotoOrientation;
(function (PhotoOrientation) {
    PhotoOrientation[PhotoOrientation["Landscape"] = 0] = "Landscape";
    PhotoOrientation[PhotoOrientation["Portrait"] = 1] = "Portrait";
    PhotoOrientation[PhotoOrientation["Square"] = 2] = "Square";
    PhotoOrientation[PhotoOrientation["Panorama"] = 3] = "Panorama";
})(PhotoOrientation || (PhotoOrientation = {}));
class Picture {
    //*Atributos que se consideran necesarios para construir objetos
    constructor(id, title, orientation) {
        this.id = id;
        this.title = title;
        this.orientation = orientation;
    }
    //*Comportamiento
    toString() {
        return `
    [
      id: ${this.id},
      title: ${this.title},
      orientation: ${this.orientation}
    ]
    `;
    }
}
class Album {
    constructor(id, title) {
        this.id = id;
        this.title = title;
        this.pictures = []; //*Inicializamos el array vacío
    }
    addPicture(picture) {
        this.pictures.push(picture);
    }
}
const album = new Album(1, 'Personal Pictures');
const picture = new Picture(1, 'Selfie', PhotoOrientation.Square);
album.addPicture(picture);
//console.table(album)
//console.table(picture)
//console.table({picture})
console.log(album); //* Imprime el objeto
console.table({ album }); //* Como manejamos un objeto, podemos usar console.table
console.table(album.pictures); //* Como tenemos un array dentro del objeto, también podemos usar console.table

Me ha gustado la forma en que se dan las clases, primero teoría y luego un ejemplo sencillo.

Agregó un aporte de como utilizar el ejemplo de clases a partir de un caso diferente (Pedidos de Comida)

// CLASSES
/*  Las clases y en general la POO pueden ser usadas
    a partir de ES5, así como todos sus conceptos.
*/

/**
 * A partir de un ejemplo con una aplicacion de pedidos de comida
 * existen varias entidades:
 * Usuarios: Quies hacen los pedidos
 * order_status: Enum con estado de los pedidos
 * Pedidos: La conjuncion de los pedidos que se van a ordenar
 * Comida: La comida que se esta pidiendo
 * 
 *          Usuario ---> Comida --> Orden --> Status
 */

// tipo de dato enum para almacenar es estado de las ordenes
enum OrderStatus {
    not_attended = 0,
    attended = 1,
    ready = 2,
    done = 3
}

// CLASE DE FOOD PARA CREAR NUEVOS ALIMENTOS
class Food {

    id_food: number;
    food_name: string;
    price: number;
    description: string;

    constructor(
        id_food: number,
        food_name: string,
        price: number,
        description: string
    ) {
        this.id_food = id_food;
        this.food_name = food_name;
        this.price = price;
        this.description = description;
    }
}


// CLASE PARA GUARDAR LAS ORDENES DE LOS USUARIOS
class UserOrders {
    id_order: number;
    id_user: User;
    order_status: OrderStatus;
    food_order: Array<[Food]> = [];

    constructor(id_order: number, id_user: User, order_status: OrderStatus) {
        this.id_order = id_order;
        this.id_user = id_user;
        this.order_status = order_status;
    }

    addNewFoodToOrder(food: Food) {
        this.food_order.push([food]);
    }
}

//CLASE DE USER PARA MANEJAR A LOS USUARIOS
class User {

    id_user: number;
    user_name: string;
    isPro: boolean;

    constructor(id_user: number, user_name: string, isPro: boolean) {
        this.id_user = id_user;
        this.user_name = user_name;
        this.isPro = isPro;
    }

    getMyUser() {
        console.log(this.id_user, this.user_name, this.isPro);
    }
}

// CREAMOS NUESTRO USUARIO QUE CREARA LOS PEDIDOS
const my_new_user: User = new User(1, 'Mike', true);
console.table(my_new_user);

// CREAMOS LOS PLATILLOS EXISTENTES
const platillo_1: Food = new Food(1, 'Tortas', 20.00, 'Tortas de un Ingrediente');
console.table(platillo_1);
const platillo_2: Food = new Food(2, 'Enchiladas', 10.00, 'Orden de 4 enchiladas.');
console.table(platillo_2);

// CREAMOS UNA NUEVA ORDEN DE COMIDA
const nueva_orden: UserOrders = new UserOrders(1, my_new_user, OrderStatus.not_attended)
nueva_orden.addNewFoodToOrder(platillo_1);
nueva_orden.addNewFoodToOrder(platillo_2);
console.log(nueva_orden.food_order);

“Pero veámoslo de una manera práctica”… Me encanta aprender practicando

Clases
Diferentes entidades que guardan relación en común. Abstracción de un conjunto de objetos. Propiedades & funciones. Para crear objetos con estas clases constructor(función), valores que recibo como parámetro y asignarlos a las propiedades this.propiedades.

export {};

enum PhotoOrientation {
    Landscape,
    Portrait,
    Square,
    Panorama
}

class Picture {
    // Propiedades
    id: number;
    title: string;
    orientation: PhotoOrientation;

    constructor(id: number, 
                title: string, 
                orientation: PhotoOrientation) {
        this.id = id;
        this.title = title;
        this.orientation = orientation;
    }

    // Comportamiento
    toString() {
        return `[id: ${this.id}, 
                 title: ${this.title}, 
                 orientation: ${this.orientation}]`;
    }
}

class Album {
    id: number;
    title: string;
    pictures: Picture[];

    constructor(id: number, title: string) {
        this.id = id;
        this.title = title;
        this.pictures = [];
    }

    addPicture(picture: Picture) {
        this.pictures.push(picture);
    }
}

const album: Album = new Album(1, 'Personal Pictures');
const picture: Picture = new Picture(1, 'Platzi session', PhotoOrientation.Square);
album.addPicture(picture);

console.log('album', album);

code

para el console log podemos hacer {album} y sera lo mismo que (‘album’, album)

No me gusta como JS implementa POO, guardaba la esperanza que TS ayudara en algo, pero se acaba de desvanecer esa esperanza

class Album {

    id: number;
    title: string;
    pictures: Picture[] = [];

  constructor (title:string){
        this.title = title;
    }

  constructor (id: number){
        this.id = id;
    }
}