프론트엔드 첫걸음

클래스와 오브젝트 본문

개발 공부/Javascript

클래스와 오브젝트

차정 2022. 8. 7. 20:07

getter setter


setter를 설정하면 값을 할당하려 할 때 프로퍼티의 값이 직접 바뀌지 않고 setter가 호출된다.
getter를 설정하면 값을 읽을때 getter를 통해 읽는다. 

class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;

    }

    get age() {
        return this.age;
    }

    set age(value) {
       this.age = value;

    }
}

const user1 = new User('Steve', 'Job', 11);
console.log(user1.age);



user1 생성 시 constructor에서 -1로  나이를 지정(=age)
-> 
 set age를 호출함
-> set age내에서  this.age에 값을 할당 
-> set age 호출
...무한반복된다

console.log(user1.age)에서 user1.age로 값을 읽으려 함
-> get age 호출
-> get age 내에서 this.age로 나이를 읽으려 함
-> get age 호출
...무한반복된다.

 

class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;

    }

    get age() {
        return this._age; //이렇게 getter와 setter내에서 쓰이는 속성값을 다르게 해서 무한재귀 방지
    }

    set age(value) {
       this._age = value < 0 ? 0 : value;

    }
}

const user1 = new User('Steve', 'Job', 11);
console.log(user1.age); //.age로 접근할 수 있는것은 getter와 setter 때문
  • 이때 User클래스의 field는 firstName, lastName, _age 세개
  • user의 나이는 _age 에 저장되고, 프로퍼티에 접근하는 것은 getter와 setter를 통해 이뤄진다.
  • getter와 setter를 사용해서 나이를 -1 로 설정하는 것 등 을 방지한다.

“ 기술적으론 외부 코드에서 user._age 을 사용해 이름에 바로 접근할 수 있습니다. 그러나 밑줄_로 시작하는 프로퍼티는 객체 내부에서만 활용하고, 외부에서는 건드리지 않는 것이 관습입니다.


user1 생성 시 constructor에서 -1로  나이를 지정(=age)
->  
 set age를 호출함
-> set age내에서  this._age에 값을 할당 
-> 내부 프로퍼티인 _age에 값 할당  (무한반복되지않음)


console.log(user1.age)에서 user1.age로 값을 읽으려 함
-> get age 호출
-> get age 내에서 this._age로 나이를 읽으려 함
-> 내부프로퍼티 _age 값 읽음 (무한반복되지않음)



 

private Field

class Experiment {
    publicField = 2;
  #privateField = 0;

}

const experiment = new Experiment();
console.log(experiment.publicField) //2
console.log(experiment.privateField) //0
  • ‘#’ 이 붙은 것은 private field ~ 클래스 내부에서만 접근가능
  • 아직 바벨에서만 사용가능한 신기능 (사용하기에 이르다)

 

static

오브젝트와 상관없이 클래스에서 공통적으로 사용하는 것에 사용.

class Article {
    static publisher = 'Park'
  constructor(articleNumber) {
      this.articleNumber = articleNumber;
  }
  static printPublisher() {
      console.log(Article.publisher);
  }
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);  //article에 상관없이 publisher는 Park
Article.printPublisher();        //article에 들어오는 데이터와 상관없이 출력

 

상속

class Shape {
    constructor(width, height, color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    draw() {
        console.log(`drawing ${this.color} color!`);
    }

    getArea() {
        return this.width * this.height;
    }
}
class Rectangle extends Shape {} //shape을 상속받는 rectangle
class Triangle extends Shape {
    draw() {
        super.draw(); //부모의 draw 사용
        console.log('▲');
    }
    //오버라이딩 - 필요한 함수만 재정의
    getArea() {
        return (this.width * this.height) / 2;
    }
}

상속받아서 아래와 같이 사용가능

const rectangle = new Rectangle(20, 20, "blue");
rectangle.draw();
console.log(rectangle.getArea());

const triangle = new Triangle(20, 20, "red");
triangle.draw();
console.log(triangle.getArea());

 

instanceOf

이 인스턴스가 클래스의 인스턴스인지 확인하는 메서드

console.log(rectangle instanceof Rectangle); //true
console.log(triangle instanceof Rectangle); //false
console.log(triangle instanceof Triangle); //true
console.log(triangle instanceof Shape); //true
console.log(rectangle instanceof Object); //true , 자바스크립트의 모든 오브젝트는 Object상속받은것
console.log(rectangle.toString());       //따라서 triangle도 Object의 toString 사용가능

// toString 오버라이드 가능
class Rectangle extends Shape {
    toString() {
        return `Rectangle`;
    }
}

 

 

 

출처

[드림코딩 엘리] 자바스크립트 6. 클래스와 오브젝트의 차이점(class vs object)

https://www.youtube.com/watch?v=_DLhUBWsRtw


getter, setter 잘 설명된 블로그
https://think0wise.tistory.com/27