티스토리 뷰

const obj = {
  log: ['a', 'b', 'c'],
  // 메서드
  latest() {
    if (this.log.length === 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
}; 

console.log(obj.latest()); // c
const obj = {
  log: ['a', 'b', 'c'],
  // getter
  get latest() {
    if (this.log.length === 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
}; 

console.log(obj.latest()); // Uncaught TypeError: obj.latest is not a function
console.log(obj.latest); // c

동적으로 계산된 값을 반환하는 프로퍼티에 접근하고 싶거나, 명시적인 메서드 호출 없이 내부 변수의 상태를 반영하고 싶을 때, getter를 사용할 수 있다.

get을 떼면 메서드인데, get을 붙여서 마치 프로퍼티인 것처럼 접근할 수 있다. 그래서인지 이걸 pseudo-property 라고 부른다. 그리고 다른 프로퍼티와 달리, 이 pseudo-property다른 값을 할당하려고 해도 바뀌지 않는다.

getter는 접근되기 전에는 그 프로퍼티의 값을 계산하지 않는다. 필요로 하기 전까지는 계산하지 않으므로, 만약 한 번도 필요하지 않았다면 계산 비용을 지불할 필요가 없다.

그리고 호출될 때 한 번 계산한 뒤 그 값을 캐시하고 다음에 다시 호출되면 재계산하는 것이 아니라 캐시된 값을 반환한다. 그러므로 getter로 설정할 프로퍼티는 값이 바뀌지 않고 재계산할 필요가 없는 값이어야 한다.

defineProperty와 차이

const o = {a: 0};

Object.defineProperty(o, 'b', { get: function() { return this.a + 1; }});

console.log(o.b); // 1
o.hasOwnProperty('b'); // true

definedProperty로도 거의 비슷한 기능을 구현할 수 있지만, 클래스 안에서 정의했을 때 살짝 다른 점이 있다. defineProperty는 해당 객체 자체의 프로퍼티로 정의되고, 클래스 안에서 getter를 사용하면 객체의 프로토타입에 프로퍼티가 정의된다.

class O {
    a = 0;
    get b() {
        return this.a + 1;
    }
}

const o = new O();
console.log(o.b); // 1
o.hasOwnProperty('b'); // false

Ref

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

 

getter - JavaScript | MDN

getter The get syntax binds an object property to a function that will be called when that property is looked up. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, ple

developer.mozilla.org

 

'공부일지(TIL) > JavaScript' 카테고리의 다른 글

[JavaScript] 비동기 프로그래밍  (0) 2021.04.04
[JavaScript] 콜백 함수의 this  (0) 2021.04.01
[JavaScript] 숫자(Number) 타입  (0) 2021.03.23
[JavaScript] 어휘 구조  (0) 2021.03.23
[JavaScript] Protobuf 직렬화  (0) 2021.03.18
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함