π¨ Frontend/JavaScript
π¦Vanilla JS β₯ ν΄λμ€ (μλ° class VS μλ°μ€ν¬λ¦½νΈ class)
kongmi
2023. 3. 29. 18:02
- μλ°μ€ν¬λ¦½νΈμμμ
class
μ μλ°μclass
λ μ μ¬ν μ μ΄ λ§μ΅λλ€. - 곡ν΅μ¬νμ λ°λ‘ λ€λ£¨μ§ μκ³ , μ°¨μ΄μ μ λν΄μλ§ λ€λ£¨κ² μ΅λλ€.
μ°¨μ΄μ
- β μλ° ν΄λμ€λ μΈν°νμ΄μ€λ₯Ό μ¬μ©νμ¬ λ€μ€ μμμ λͺ¨λ°©ν μ μμ΅λλ€λ§,
π¦ μλ°μ€ν¬λ¦½νΈμμλ μΈν°νμ΄μ€ κ°λ μ΄ μμΌλ―λ‘ λ€λ₯Έ λ°©λ²μ μ¬μ©ν΄μΌ ν©λλ€. - β μλ° ν΄λμ€μμλ
super
ν€μλλ₯Ό μ¬μ©νμ¬ μμ ν΄λμ€μ μμ±μλ₯Ό λͺ μμ μΌλ‘ νΈμΆν΄μΌ ν©λλ€.
π¦μλ°μ€ν¬λ¦½νΈ ν΄λμ€μμλsuper
ν€μλλ₯Ό μ¬μ©νμ¬ μμ ν΄λμ€μ 'μμ±μ'λ₯Ό νΈμΆνλ κ² μ΄μΈμλ,super
ν€μλλ₯Ό μ¬μ©νμ¬ μμ ν΄λμ€μ 'λ©μλ'λ₯Ό νΈμΆν μ μμ΅λλ€. - βμλ° ν΄λμ€μμλ μμ ν΄λμ€μ λ©μλλ₯Ό
super
ν€μλλ₯Ό μ¬μ©νμ¬ μ€λ²λΌμ΄λ©μ λ°©μ§ν μ μμ΅λλ€λ§,
π¦μλ°μ€ν¬λ¦½νΈμμλ μ€λ²λΌμ΄λ©μ λ°©μ§νλ ν€μλκ° μκΈ° λλ¬Έμ λ€λ₯Έ λ°©λ²μ μ¬μ©ν΄μΌ ν©λλ€.
μμ
class Vehicle {
constructor(brand, model, year, color, speed) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
this.speed = speed;
}
getBrand() {
return this.brand;
}
getModel() {
return this.model;
}
getYear() {
return this.year;
}
getColor() {
return this.color;
}
getSpeed() {
return this.speed;
}
accelerate(amount) {
this.speed += amount;
console.log(`The ${this.brand} ${this.model} is now going ${this.speed}km/h.`);
}
break(amount) {
this.speed = Math.max(0, this.speed - amount);
console.log(`The ${this.brand} ${this.model} is now going ${this.speed}km/h.`);
}
static getNumberOfWheels() {
return 0;
}
}
class Car extends Vehicle {
constructor(brand, model, year, color, speed, numDoors) {
super(brand, model, year, color, speed);
this.numDoors = numDoors;
}
getNumDoors() {
return this.numDoors;
}
static getNumberOfWheels() {
return 4;
}
}
class Truck extends Vehicle {
constructor(brand, model, year, color, speed, towingCapacity) {
super(brand, model, year, color, speed);
this.towingCapacity = towingCapacity;
}
static getNumberOfWheels() {
return 6;
}
}
const myCar = new Car("νλ", "μ λ€μμ€G80", 2022, "BLACK", 180, "4");
console.log(myCar.getBrand());
myCar.accelerate(30);
myCar.break(10);
console.log(Car.getNumberOfWheels());
console.log("\n");
const myCar2 = new Truck("κΈ°μ", "λ΄κ³ ", 2010, "WHITE", 100, 10000);
console.log(myCar2.getModel());
console.log(myCar2.getColor());
myCar2.accelerate(50);
myCar2.break(80);
console.log(Truck.getNumberOfWheels());