TIL/멋쟁이사자처럼 FE스쿨 2기

[Day 35] JS 클로저 활용 & Class

Dahee.jo 2022. 5. 18. 23:55
SMALL

클로저를 이용한 모듈패턴, 사용자 정의 타입 패턴, 혼합 패턴

 

1. 모듈패턴

function Person(){
	let age=15; //외부에서 접근할 수 없는 값
    
    return {
    	getAge: function(){
        	return age
        },
        setAge: function(updatedAge){
        	age = updatedAge
        }
    }
}

const person = new Person();
console.log(person.getAge()); //15
console.log(person.age);//undefined
person.setAge(40)
console.log(person.getAge());//40

 

2. 사용자 정의 타입 패턴

function Person(){
	this.age=13;
}

Person.prototype.getAge=function(){
	return this.age
}

Person.prototype.setAge=function(updatedAge){
	return this.age = updatedAge
}

const person = new Person();
console.log(person.getAge()) //13
person.setAge(20);
console.log(person.getAge()) //20

 

3. 모듈+사용자정의 혼합

function Person() {
	let age=10;
    
    function innerPerson(){}
    innerPerson.prototype.getAge=function(){
    	return age
    }
    
    return innerPerson;
}

const Person = new Person();
const person = new Person();
console.log(person.getAge());//10
console.log(person.age)//undefined


//즉시실행함수로 인스턴스 2번 만드는 불편함 없앰.
const Person = (function(){
	let age=10;
    function innerPerson(){}
    innerPerson.prototype.getAge=function(){
    	return age
    }
    return innerPerson
   }
  )();
  
  
const person = new Person();
console.log(person.getAge());//10
console.log(person.age)//undefined

 


클래스

 

생성자+프로토타입으로 쓴 코드와 클래스로 쓴 코드 비교

function Robot(name){
    this.name = name;
}

Robot.prototype.sayYourName = function(){
    console.log(`제 이름은 ${this.name}입니다.`);
}

const bot1= new Robot('재현');
class RobotClass{
    constructor(name){
        this.name = name
    }

    sayYourName(){
        console.log(`제 이름은 ${this.name}입니다.`);
    }
} // 클래스 안에선 function 키워드를 생략한다.
//prototype 설정필요없이 같은 메서드를 공유한다.

 

 

클래스 상속

부모 클래스
자식 클래스

constructor 안의 내용이 같으면 생략이 가능하다.

새로운 프로퍼티가 추가되는 경우, 부모의 프로퍼티를 super()를 이용해서 반드시 첫번째로 적어준 후

그다음 새로운 프로퍼티를 추가한다. 

 

비공개(private) 프로퍼티

 

get, set 키워드를 사용 시 비공개 프로퍼티에 너무 쉽게 접근할 수 있으므로 주의가 필요하다.

 

 

반응형