Codestates SEB FE 42기/정리노트
S2 unit2 | [javascript] 클로저 모듈 패턴 / 클래스 생성
2realzoo
2022. 11. 19. 12:46
📌 클로저 모듈 패턴
✔ 메서드
: 객체 안에서 정의된 함수 🔗
: 화살표 함수 방식을 사용하지 않음
=> 다른 함수는 생성될 때의 문맥에 따라 this를 생성하지만 화살표 함수는 자신의 this를 가지지 않기 때문에 메서드 내에서 사용할 수 없다. 🔗
let counter1 = {
value: 0,
increase: function() {
this.value++ // 메서드 호출을 할 경우, this는 counter1을 가리킵니다
},
decrease: function() {
this.value--
},
getValue: function() {
return this.value
}
}
counter1.increase()
counter1.increase()
counter1.increase()
counter1.decrease()
counter1.getValue() // 2
counter 객체 속성으로 value와 메서드를 정의하였다.
⇒ 재사용 불가능
✔ 클로저 모듈 패턴
function makeCounter() {
let value = 0;
return {
increase: function() {
value++;
},
decrease: function() {
value--;
},
getValue: function() {
return value;
}
}
}
let counter1 = makeCounter()
counter1.increase()
counter1.getValue() // 1
let counter2 = makeCounter()
counter2.decrease()
counter2.decrease()
counter2.getValue() // -2
클로저의 성질을 이용하여 변수에 할당하여 새로운 객체를 만들 수 있도록 한다.
makeCounter함수가 종료되었지만 내부 함수에서 value를 사용할 수 있기 때문에
counter1 과 counter2는 별개의 value를 갖고 있다.
⇒ 재사용 가능
📌 클래스와 인스턴스
✔ 객체지향 프로그래밍
하나의 모델이 되는 청사진으로 여러 개의 객체를 만드는 프로그래밍 패턴
청사진 = Class
청사진으로 만든 객체 = Instance
class 규칙
- 첫번째 글자를 대문자로 적는다.
- 일반 명사로 이름 붙인다.
constructor(생성자) 함수
: instance가 초기화 될 때 실행되는 함수, return값을 만들지 않음 🔗
- "constructor" 라는 이름의 메서드는 하나의 클래스에 오직 하나만 존재 가능 => 두 개 이상의 constructor 메서드를 정의하면 SyntaxError가 발생
- 생성자 함수 작성하지 않으면 기본 생성자(default constructor)가 제공됨
- 부모 클래스가 있고, 자식 클래스가 생성자 함수를 작성하지 않았다면 부모 생성자를 부름
this
: 동작하는 코드를 가진 객체 🔗
new 연산자
: 객체의 새로운 instance를 생성하는 연산자 🔗
- new Date()🔗Date 생성자
- Date()가 constructor이므로 새로운 인스턴스를 만들어낸다.
✔ ES5
function Student (name, age, grade){ // class와 constructor
this.name = name;
this.age = age;
this.grade = grade;
}
student.prototype.study(){ //prototype 객체로 만든 메서드
console.log(`${this.name}가 공부를 시작합니다`)
}
let student1 = new Student('anna', '17', 'A') //instance
prototype
: ES5에서 메서드를 만들 때 사용하는 객체 🔗
✔ ES6
class Student {
constructor(name, age, grade){
this.name = name;
this.age = age;
this.grade = grade;
}
study(){
console.log(`${this.name}가 공부를 시작합니다`)
}
}
let student1 = new Student('anna', '17', 'A') //instance
class 🔗
: ES6에서 class를 생성하는 문법