Getter and Setter

wonyoung·2024년 1월 30일

Javascript

목록 보기
3/36
class Model{
	name;
    year;
    
    constructor(name,year){
    this.name = name;
    this.year = year;
    }
    
    /**
    * 1) 데이터를 가공해서 새로운 데이터를 반환할때
    * 2) private한 값을 반환할 때
    */
    get nameAndYear(){
    	return `${this.name}-${this.year}`;
    }
    
    /**
    * 
    *
    */
    set setName(name){  // 파라미터 1개 필수
    	this.name = name;
    }
}
const wonYoung = new Model('이원영', 1997);
console.log(wonYoung);
console.log(wonYoung.nameAndYear);

wonyoung.setName = '김원영';
console.log(wonYoung) // Model{ name : 김원영, year: 1997}
class Model2{
	#name; // 프라이빗 프로퍼티
    year;
    
    constructor(name,year){
    this.#name = name;
    this.year = year;
    }

    get name(){ 
    	return this.#name;
    }

    set name(name){  // 보통 바꾸고 싶은 프로퍼티 이름과 겹치게 사용, 파라미터 1개 고정
    	this.#name = name;
    }
}
const wonYoung2 = new Model2('이원영', 1997);
console.log(wonYoung2); // year만 보임
console.log(wonyoung2.name) // getter실행으로 실행값 '이원영'

wonYoung2.name = '김원영';
console.log(wonYoung2.name); // 김원영

강의출처 https://youtu.be/ZOVG7_41kJE?si=6V3c-ctH40mxdch1

profile
😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀

0개의 댓글