extends
, super
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const animal = new Animal("Generic Animal");
animal.speak(); // "Generic Animal makes a noise."
const dog = new Dog("Buddy");
dog.speak(); // "Buddy barks."
class.instance
class Singleton {
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.value = 42;
Singleton.instance = this;
}
}
const s1 = new Singleton();
const s2 = new Singleton();
console.log(s1 === s2); // true (both references point to the same instance)
class Car {
constructor() {
this.type = 'Car';
}
}
class Truck {
constructor() {
this.type = 'Truck';
}
}
function vehicleFactory(vehicleType) {
if (vehicleType === 'car') {
return new Car();
} else if (vehicleType === 'truck') {
return new Truck();
}
return null;
}
const vehicle1 = vehicleFactory('car');
console.log(vehicle1.type); // "Car"
const vehicle2 = vehicleFactory('truck');
console.log(vehicle2.type); // "Truck"