Menu
Coddy logo textTech

Construcción de objetos

Parte de la sección Programación Orientada a Objetos del Journey de JavaScript de Coddy — lección 49 de 56.

Ahora que entendemos los problemas con la herencia profunda y la relación "tiene-un" (has-a), aprendamos cómo construir objetos combinando componentes pequeños y reutilizables. ¡Este enfoque nos brinda la máxima flexibilidad! 

El patrón básico:

// Paso 1: Crear componentes pequeños y enfocados
class Engine {
  constructor(power) {
    this.power = power;
  }
  
  start() {
    console.log(`Engine (${this.power}HP) starting...`);
  }
}

class Wheels {
  constructor(count) {
    this.count = count;
  }
  
  rotate() {
    console.log(`${this.count} wheels rotating`);
  }
}
// Paso 2: Construir objetos combinando componentes
class Car {
  constructor(brand, enginePower, wheelCount) {
    this.brand = brand;
    this.engine = new Engine(enginePower);    // TIENE UN motor
    this.wheels = new Wheels(wheelCount);     // TIENE ruedas
  }
  
  drive() {
    console.log(`${this.brand} is driving:`);
    this.engine.start();
    this.wheels.rotate();
  }
}
// Paso 3: Usar el objeto compuesto
const myCar = new Car('Toyota', 150, 4);
myCar.drive();
// Salida:
// Toyota is driving:
// Engine (150HP) starting...
// 4 wheels rotating

El verdadero poder: mezclar y combinar componentes:

// Componentes más especializados
class TurboCharger {
  boost() {
    console.log('Turbo engaged! Extra power!');
  }
}

class SoundSystem {
  constructor(type) {
    this.type = type;
  }
  
  playMusic() {
    console.log(`Playing music on ${this.type} sound system`);
  }
}
// Construye diferentes coches con diferentes combinaciones
class SportsCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(300);
    this.wheels = new Wheels(4);
    this.turbo = new TurboCharger();      // El coche deportivo tiene turbo
    this.soundSystem = new SoundSystem('Premium'); // Y buen sonido
  }
  
  raceMode() {
    console.log(`${this.brand} in race mode:`);
    this.engine.start();
    this.turbo.boost();
    this.wheels.rotate();
    console.log('VROOOOM!');
  }
  
  cruise() {
    console.log(`${this.brand} cruising:`);
    this.engine.start();
    this.wheels.rotate();
    this.soundSystem.playMusic();
  }
}
class EconomyCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(100);
    this.wheels = new Wheels(4);
    // Sin turbo para coche económico
    this.soundSystem = new SoundSystem('Basic'); // Solo sonido básico
  }
  
  drive() {
    console.log(`${this.brand} driving efficiently:`);
    this.engine.start();
    this.wheels.rotate();
    this.soundSystem.playMusic();
  }
}
// ¡Mira qué flexible es esto!
const ferrari = new SportsCar('Ferrari');
const honda = new EconomyCar('Honda');

ferrari.raceMode();  // ¡Tiene turbo boost!
ferrari.cruise();    // ¡Tiene sonido premium!

honda.drive();       // Solo funciones básicas

¡Este enfoque te brinda la flexibilidad de mezclar y combinar comportamientos sin complejas cadenas de herencia!

challenge icon

Desafío

Completa los métodos de SmartBulb en el archivo SmartBulb.js.

  1. Implementa el método activate() para encender la luz.
  2. Implementa el método adjustBrightness() para establecer el brillo y registrar exactamente: Brightness set to ${this.brightness.level}%

Hoja de referencia

Los objetos se pueden construir combinando componentes pequeños y reutilizables en lugar de utilizar una herencia profunda. Esto se llama composición y sigue la relación "tiene-un" (has-a).

Patrón de composición básico:

// Paso 1: Crear componentes pequeños y enfocados
class Engine {
  constructor(power) {
    this.power = power;
  }
  
  start() {
    console.log(`Engine (${this.power}HP) starting...`);
  }
}

// Paso 2: Construir objetos combinando componentes
class Car {
  constructor(brand, enginePower) {
    this.brand = brand;
    this.engine = new Engine(enginePower);  // TIENE-UN motor
  }
  
  drive() {
    this.engine.start();
  }
}

Mezcla y combina componentes para mayor flexibilidad:

class TurboCharger {
  boost() {
    console.log('Turbo engaged!');
  }
}

class SportsCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(300);
    this.turbo = new TurboCharger();  // Añadir componente turbo
  }
  
  raceMode() {
    this.engine.start();
    this.turbo.boost();
  }
}

class EconomyCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(100);
    // Sin componente turbo
  }
}

La composición permite construir objetos con diferentes combinaciones de características sin cadenas de herencia complejas.

Pruébalo tú mismo

import { SmartBulb } from './SmartBulb.js';

const bedroomLight = new SmartBulb('warm white');

console.log('1. Activating light:');
bedroomLight.activate();

console.log('\n2. Adjusting brightness:');
bedroomLight.adjustBrightness(75);
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Programación Orientada a Objetos