JS - Class getter setter

JD·2021년 9월 30일
0

Getter,Setter

java와 차이가 있으니 주의하면서 사용해야 합니다

class User {
	constructor(){
		this._name = '';
	}
	
	get name() {
		return this._name;		
	}
	
	set name(newName){
		this._name = newName;
	}
}

const obj = new User();
obj.name = '홍길동';
console.log(obj.name);

getter 와 메소드 차이

class Rect{
	constructor(height,width){
		this.height = height;
		this.width = width;
	}
	
	get area() {
		return this.calc();
	}
	
	calc(){
		return this.height * this.width;
	}
	
}

var obj = new Rect(10,5);
console.log(obj.area);
console.log(obj.calc());

0개의 댓글