Skip to main content

[JavaScript] getter, 일반 함수차이


자바스크립트 getter / 함수 호출 차이

class Person {
  constructor(first, last, nickname) {
    this.first = first;
    this.last = last;
    this.nickname = nickname;
  }

  // 일반 메서드
  greet() {
    return `Hello, my name is ${this.first} ${this.last}`;
  }

  // getter
  get nicknames() {
    return `Your nickname is ${this.nickname}`;
  }
}

const alberto = new Person("Alberto", "Montalesi", "Albie");

console.log(alberto.greet());     // "Hello, my name is Alberto Montalesi" → 괄호 필요
console.log(alberto.nicknames);   // "Your nickname is Albie" → 괄호 없음
  • greet() 같은 일반 메서드는 괄호를 붙여야 호출
  • nicknames 같은 getter는 속성처럼 접근
  • 둘 다 내부에서 this통해 객체 속성 접근 가능
  • getter은 주로 계산된 속성값, 메서드는 행동 수행


계산된 속성값

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

  // 계산된 속성값: 넓이
  get area() {
    return this.width * this.height;
  }

  // 계산된 속성값: 둘레
  get perimeter() {
    return 2 * (this.width + this.height);
  }
}

const box = new Rectangle(5, 10);

console.log(box.area);      // 50  ← 저장하지 않고 계산
console.log(box.perimeter); // 30  ← 저장하지 않고 계산
  • 여기서 area나 perimeter는 실제로 객체에 저장된 값이 아니다.
  • width와 height를 바꾸면 getter 가 자동으로 새로운 값을 계산해서 보여준다.
  • getter를 이용하면 계산된 속성값을 마치 객체 속성처럼 깔끔하게 다룰수 있다.
box.width = 7;
console.log(box.area); // 70 ← 자동으로 업데이트


문자열 처리

class Person {
  constructor(first, last, nickname) {
    this.first = first;
    this.last = last;
    this.nickname = nickname;
  }

  // 계산된 속성값: 전체 이름
  get fullName() {
    return `${this.first} ${this.last}`;
  }

  // 계산된 속성값: 닉네임 소개
  get nicknameIntro() {
    return `Hello! You can call me "${this.nickname}"`;
  }
}

const alberto = new Person("Alberto", "Montalesi", "Albie");

console.log(alberto.fullName);       // "Alberto Montalesi"
console.log(alberto.nicknameIntro);  // 'Hello! You can call me "Albie"'

// 속성을 바꾸면 getter도 자동 계산
alberto.nickname = "Monty";
console.log(alberto.nicknameIntro);  // 'Hello! You can call me "Monty"'
  • fullName은 first와 last를 합쳐서 계산
  • nicknameIntro는 nickname으로 문자열을 만들어서 반환
  • getter라서 속성처럼 접근 가능하고 값이 바뀌면 자동으로 계산됨