[JS딥다이브 개념정리] 프로퍼티 어트리뷰트

piper ·2024년 1월 10일
0

Java Script 

목록 보기
15/22

프로퍼티 어트리뷰트는 자바스크립트의 객체동작을 제어하고 정의하는데 중요한 역할을 한다.
자바스크립트 객체의 속성(attribute)에 대한 설명을 나타내는데 사용되는 메타데이터로
각각의 객체 속성은 value(값), Writable(쓰기 가능 여부), Enumerable(열거 가능 여부), Configurable(설정가능여부) 라는 속성(attribute)을 갖는다.

  1. 데이터 프로퍼티: 객체에 일반적으로 사용되는 프로퍼티 유형
    Object.defineProperty() 메서드나 객체 리터럴을 통해 설정해줄수 있다.
let obj = {};
Object.defineProperty(obj,'myProperty',{
value: 42,
writable: false,
enumerable: true,
configurable: true
});

console.log(obj) // { myProperty: 42 }


let obj2 ={
myProperty:{
value:42,
writable: false,
enumerable: true,
configurable: true
}
}

console.log(obj2); // { myProperty: { value: 42, writable: false, enumerable: true, configurable: true } }
console.log(obj2.myProperty); // { value: 42, writable: false, enumerable: true, configurable: true }

Object.defineProperty() 메서드로 속성을 정의할 때는 해당 속성이 직접 객체에 추가되지 않는다. 대신, 명시적으로 정의한 속성을 가리키는 프로퍼티를 생성하게 된다.

따라서 console.log(obj)에서는 myProperty가 직접 나타나지 않고, 해당 객체에 대한 뷰(view)를 제공하는 프로퍼티를 출력한다. Object.defineProperty() 메서드를 사용하면 직접적으로 속성이 객체에 추가되지 않기 때문에 외부에서는 해당 속성을 직접 볼 수 없다.

  1. 접근자 프로퍼티 (Accessor Property): 값을 직접 지정하지 않고, 대신 값을 가져오거나 정의.
    get 함수는 프로퍼티 값을 읽을때, set 함수는 프로퍼티에 값을 할당할 때 호출
let obj = {
  _myValue: 0,
  get myAccessorProperty() {
    return this._myValue;
  },
  set myAccessorProperty(value) {
    this._myValue = value;
  }
};
profile
연습일지

0개의 댓글