내일배움캠프 스파르타 코딩클럽
오늘은 쉽게 이해하면서 좀 더 재미있는 걸 가져 와봤다.
JavaScript 5주차 강의에 나오는 클래스 와 인스턴스인데 개념을 두고두고 기억하기 위해서 이렇게 작성해본다.
// 클래스는 설계도
class Person {
constructor(name, age) { //this는 인스턴스
this.name = name;
this.age = age;
}
// 메서드 형태의 동사 표현(verb)
//동사(verb) 처럼 동작
sayHello() {
console.log(`${this.name}님 안녕하세요!`)
}
sayAge() {
console.log(`내 나이는 ${this.age}살 이에요!`)
}
}
// 설계도를 통해 인스턴스를(실제 사물) 아래와 같이 만들 수 있다.
const person1 = new Person("홍길동", "30");
const person2 = new Person("홍길순", "25");
person1.sayHello(); // 홍길동님 안녕하세요!
person2.sayHello(); // 홍길순님 안녕하세요!
person1.sayAge(); // 내 나이는 30살 이에요!
person2.sayAge(); // 내 나이는 25살 이에요!
내 나름대로 기본적인 부분을 기억하기 위해 쉬운 암기법 클설인사메동~ (크리스마스+설날+인사+메롱)
사실 그냥 익숙해져서 따로 암기할 필요가 없을 수 있겠지만
내 경험상 모든 부분의 개념과 기초는 필요 없는 부분이 없으며 익숙해지면 결국 머리와 몸은 알지만 누군가에게
설명하기는 어렵기 마련 또한 그 개념과 기초는 응용을 이뤄내기도 하고 새로운걸 생각해 내기도 한다.
그래서 계속 이런 간단한 것 이라도 상기 시키는건 좋은 결과를 나타낼 수 있다고 생각한다.
클래스 = 설계도, 인스턴스 = 사물, 메서드 = 동사 클설인사메동은 오늘부터 나와 계속 함께 할 것이다.
// [요구사항]
// 1. Car라는 새로운 클래스를 만들되, 처음 객체를 만들 때는
// 다음 네 개의 값이 필수로 입력돼야 합니다!
// (1) modelName
// (2) modelYear
// (3) type : 가솔린, 전기차, 디젤
// (4) price
// 2. makeNoise() 메서드를 만들어 클락션을 출력해주세요.
// 3. 이후 자동차를 3개 정도 만들어주세요(객체 생성)
class Car {
constructor(modelName, modelYear, type, price) {
this.modelName = modelName;
this.modelYear = modelYear;
this.type = type;
this.price = price;
}
makeNoise() {
if (this.type === 'sports' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠바바아앙~');
} else if (this.type === 'sports' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바바아앙~');
} else if (this.type === 'sedan' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠아아앙~');
} else if (this.type === 'sedan' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바아아앙~');
}
}
}
const car1 = new Car('Ferrari', 2020, 'sports', '4억')
const car2 = new Car('Ferrari', 2010, 'sports', '1억')
const car3 = new Car('cadillac', 2020, 'sedan', '1억')
const car4 = new Car('cadillac', 2010, 'sedan', '6천만')
car1.makeNoise(); // Ferrari, 2020, sports, 4억 빠바바아앙~
car2.makeNoise(); // Ferrari, 2010, sports, 1억 바바아앙~
car3.makeNoise(); // cadillac, 2020, sedan, 1억 빠아아앙~
car4.makeNoise(); // cadillac, 2010, sedan, 6천만 바아아앙~
강의에서 요구하는대로 멈추고 만들어 보라 해서 만든 클설인사메동~
강의 요구사항에서 (3) type : 가솔린, 전기차, 디젤 과 같이 풀이 전에는 가솔린, 전기차, 디젤 예시를 안적어 줬기 때문에
난 type에 sports와 sedan 으로 구분지었다.
그리고 강의에서는 다루지 않았지만 if문을 넣으면 좋을 것 같아 활용해 보았다.
결과는 위 내용 주석처럼 잘 출력되는 것을 확인 하였다.
JavaScript 중 일반 코드들과 는 다르게 class는 정말 재미있는 묘미를 나에게 안겨 주었다.
뭔가 정말 실물로 만들진 않았지만 설계하고 실물을 만든것 같은 효과를 가상으로 느끼게 해주었다.
자주자주 다뤄 볼 것이며 새로운 것을 작성할 때 마다 올려 보겠다.
2024.5.10(금)
추가적인 것을 가져왔다.
< extends > inheritance(상속) class
// 동물 전체에 대한 클래스
class Animal {
// 생성자
constructor(name) {
this.name = name;
}
// 메서드(짖다)
speak() {
console.log(`${this.name} says!`)
}
}
class Dog extends Animal { // extends 로 상속 받음
//부모에게서 내려받은 메서드를 재정의할 수 있음
// overriding...(내려받아 재정의하다.)
speak() {
console.log(`${this.name} barks!`);
}
}
const cuttyPuppy01 = new Dog("복실이");
cuttyPuppy01.speak();
바로 상속 Class
class 는 정말 재미 있는듯..
이전 것을 응용
class Car {
constructor(modelName, modelYear, type, price) {
this.modelName = modelName;
this.modelYear = modelYear;
this.type = type;
this.price = price;
}
makeNoise() {
if (this.type === 'sports' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠바바아앙~');
} else if (this.type === 'sports' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바바아앙~');
} else if (this.type === 'sedan' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠아아앙~');
} else if (this.type === 'sedan' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바아아앙~');
}
}
}
const car1 = new Car('Ferrari', 2020, 'sports', '4억')
const car2 = new Car('Ferrari', 2010, 'sports', '1억')
const car3 = new Car('cadillac', 2020, 'sedan', '1억')
const car4 = new Car('cadillac', 2010, 'sedan', '6천만')
car1.makeNoise(); // Ferrari, 2020, sports, 4억 빠바바아앙~
car2.makeNoise(); // Ferrari, 2010, sports, 1억 바바아앙~
car3.makeNoise(); // cadillac, 2020, sedan, 1억 빠아아앙~
car4.makeNoise(); // cadillac, 2010, sedan, 6천만 바아아앙~
class SportsCar extends Car {
constructor(modelName, modelYear, price) { // constructor 재 정의
//Car(부모 class)에게도 알려주기!!
super(modelName, modelYear, "sports", price);
}
}
const sportsCar1 = new SportsCar("CT5-V", "2023", "1억")
sportsCar1.makeNoise(); // CT5-V, 2023, sports, 1억 빠바아아앙~
아래는 get과 set 경로를 추적하기 위해 여러가지 방법을 써 보았다.
< get, set method >
class Car {
constructor(modelName, modelYear, type, price) {
this.modelName = modelName;
this.modelYear = modelYear;
this.type = type;
this.price = price;
}
makeNoise() {
if (this.type === 'sports' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠바바아앙~');
} else if (this.type === 'sports' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바바아앙~');
} else if (this.type === 'sedan' && this.modelYear >= 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('빠아아앙~');
} else if (this.type === 'sedan' && this.modelYear < 2014) {
console.log(`${this.modelName}, ${this.modelYear}, ${this.type}, ${this.price}`);
console.log('바아아앙~');
}
}
}
const car1 = new Car('Ferrari', 2020, 'sports', '4억')
const car2 = new Car('Ferrari', 2010, 'sports', '1억')
const car3 = new Car('cadillac', 2020, 'sedan', '1억')
const car4 = new Car('cadillac', 2010, 'sedan', '6천만')
car1.makeNoise(); // Ferrari, 2020, sports, 4억 빠바바아앙~
car2.makeNoise(); // Ferrari, 2010, sports, 1억 바바아앙~
car3.makeNoise(); // cadillac, 2020, sedan, 1억 빠아아앙~
car4.makeNoise(); // cadillac, 2010, sedan, 6천만 바아아앙~
class SportsCar extends Car {
constructor(modelName, modelYear, price, gasoline) {
//Car(부모 class)에게도 알려주기!!
super(modelName, modelYear, "sports", price);
this._gasoline = gasoline+"L"
}
get gasoline() {
return this._gasoline
}
set gasoline(value) {
this._gasoline = value+"L"
}
}
const sportsCar1 = new SportsCar("CT5-V", "2023", "1억", 60)
sportsCar1.makeNoise(); // CT5-V, 2023, sports, 1억 빠바아아앙~
console.log(sportsCar1._gasoline); // 60L
console.log(sportsCar1.gasoline); // 60L
sportsCar1.gasoline = 20
console.log(sportsCar1._gasoline); // 20L
console.log(sportsCar1.gasoline); // 20L
._gasoline 을 입력시 get, set 메서드를 거치지 않고 바로 필드 this._gasoline 값을 반환하며
.gasoline 을 입력시 get 메서드가 호출되며 this._gasoline 필드값을 반환해주고
.gasoline = 20 을 입력시 set 메서드가 호출되며 값을 매개변수(value) 에 넣고 this._gasoline = value+"L" 로 하여
필드의 this._gasoline 값은 20L 가 된다.
그리하면 ._gasoline , .gasoline 은 호출시 반환 값 this._gasline (20L) 를 반환 하게 된다.
< static method >
class Calculator {
static add (a, b) {
console.log("[계산기] 더하기를 진행합니다.");
return a + b;
}
static substract(a, b) {
console.log("[계산기] 빼기를 진행합니다.");
return a - b;
}
}
console.log(Calculator.add(3, 5)); // 8
console.log(Calculator.substract(3, 5)); // -1
간단한 계산을 위해 인스턴스를 필요로 하지 않고 static 메서드를 활용하여 위와 같이 사용할 수 있다.