TIL 27
HA를 겨우(?) 통과하고, 이번주부터 Section2를 시작했다.
객체지향 JavaScript (OOP, Object-oriented programming)
객체지향 프로그래밍 why??? ▶️ 사람이 쓰기 좋은, 보기 좋은 코드 만들기 위해
📌 객체에서 '속성(property)'이라는 용어는 키-값 쌍을 의미한다 !
Class & Instance
- class는 일종의 원형(original form)으로, 객체를 생성하기 위한 아이디어나 청사진(blueprint)이다.
- instance는 'class의 사례 (instance object)'이다.
- class는 객체를 만들기 위한 생성자(constructor)함수를 포함한다.
- 보통 class는 대문자, 그리고 일반명사로 만든다.
OOP Basic Concepts
- Encapsulation(캡슐화) : reduce complexity(복잡X) + increase reusability(재사용성)
- Inheritance(상속): reduce complexity(복잡X) + isolate impact of changes(단순화된 사용으로 인해 변화에 대한 영향 최소화)
- Abstraction(추상화): eliminate redundant code(불필요한 코드 줄여 재사용성 높임)
- Polymorphism(다형성) : refactor ugly
if / else if
statements(동일한 메소드에 대해 if/else if와 같은 조건문 대신 객체의 특성에 맞게 달리 작성하는 것이 가능해짐)
실습 예시
1️⃣ 페어와 풀었던 방식 but 추천x
class Grub {
age=0; // age의 속성은 0
color='pink'; // pink 라고하면 변수로 인식. 꼭 'pink'라 써줘야 한다.
food='jelly';
eat() {
console.log('Mmmmmmmmm jelly')
return 'Mmmmmmmmm jelly'
}
} //여기까지 입력된 Grub의 정보는 {객체형태}로 나옴 !
let grub= new Grub() //Grub안에 constructor함수를 사용할때만 let grub=new Grub(age,color,food)이렇게 명시해줌 여기선 필요x
grub.eat()
2️⃣ reference 참고 방식. 추천o
class Grub {
constructor(){
this.age=0;
this.color='pink';
this.food='jelly';
}
eat(){
return 'Mmmmmmmmm ' + this.food;
}
}
❗️ 여기서 instance 는 grub. (instance는 객체)
❗️ class Grub 은 object(객체)이다! class라는 껍데기를 가지고 있는.❗️다른 계산은 하지 않고, 순수하게 object 생성하는 함수들은
return X, Grub처럼 대문자로 시작한다!function Grub(name, age) { // class Grub 도 같은 원리 // this = {}; this.name = name; this.age = age; // return this; } 그리고, 호출 시, const grub1= new Grub ('ellie', 30); // grub1은 object console.log(grub1);
Bee로부터 상속받은 정보가 들어있는 HoneyMakerBee class
▶️ constructor() 밑에 super() 써주고, 밑에 this.사용해야 한다!
▶️ this는 생성자함수(constructor)가 생성할 객체
class HoneyMakerBee extends Bee {
constructor(){
super();
this.age=10; //여기부턴 Bee로부터 상속받은 속성값이 아닌 것들을 this.인스턴스로 나열
this.job='make honey';
this.honeyPot=0;
}
makeHoney(){
this.honeyPot++; //makeHoney 메소드는 `honeyPot`에 1씩 추가. this.honeyPot= this.honeyPot + 1 과 동일.
}
giveHoney(){
this.honeyPot--; //giveHoney 메소드는 `honeyPot`에 1씩 뺀다. this.honeyPot= this.honeyPot - 1 과 동일.
}
}
Author And Source
이 문제에 관하여(TIL 27), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jenjenhub/TIL-27저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)