객체 - 프로그래밍 도구로서의 객체

jake·2021년 8월 6일
0

JavaScript문법

목록 보기
16/21
post-thumbnail
  • Class를 만들고 그 내부에 메소드를 만들어 사용하는 것과 바깥쪽에 메소드를 사용하는 것의 차이를 알아보자.
    Class내부에 있는 메소드를 사용하면 사용자 입장에서는 객체의 메소드만 호출된다.
    바깥쪽에 선언된 메소드를 사용한다면 사용자 입장에서 메소드를 사용하기위해서 알고있어야할 정보들이 많다.
    즉, 내부에 메소드를 만들어서 사용하는 것이 좋다.
  • 타입스크립트는 객체내의 속성을 외부로 드러내지 않기위해서 private protected라는 속성 제어자를 이용해서 외부로 부터 데이터 보호가능
  • 자바스크립트도 객체내의 속성을 보호하기 위해서 클로저와 같은 테크닉을 사용할 수 밖에 없었는데, #이라는 속성이 추가됐다.
    #을 붙여주면 class내의 private 하게 사용되어 바깥쪽에서 접근할 수 없다.
    하지만 브라우 호환성을 확인해서 사용해야하고 아니면 바벨을 통해서 번역을 통해 사용해야한다.
class Circle{
    #radius;
    constructor(radius) {
        this.#radius = radius;
    }
    get radius() {
        return this.#radius;
    }
    area = () => this.#radius * this.#radius * Math.PI;
}
class Rect {
    #width;
    #height;
    constructor(width, height) {
        this.width = width;
        this.height = height;
    }
    get width() {
        return this.width;
    }
    get height () {
        return this.height;
    }
    area = () => this.#width * this.#height;
}
function calculateCircleArea(radius){
    return radius * radius * Math.PI;
}
function calculateRectArea(width, height){
    return width * height 
}
const cicle = new Circle(50);
const rect = new Rect(150,200);
<br>
console.log(calculateCircleArea(cicle.radius));
console.log(calculateCircleArea(rect.width.rect.height));
<br>
console.log(cicle.area());
console.log(rect.area());
profile
열린 마음의 개발자가 되려합니다

0개의 댓글