본문 바로가기

Programming/JavaScript

[JavaScript] 객체 내에 존재하는 속성에 접근하기

자바스크립트에서 속성은 열거가능한(enumerable) 속성열거가능하지 않은(non-enumerable) 속성으로 나뉜다.

 

또한 객체 자신이 소유하고 있는 속성과 부모에게서 상속받은 속성으로도 구분할 수 있다.

 

메서드에 따라 객체의 속성에 접근할 수 있는 범위가 달라진다.

 

다음 코드의 예제로 살펴보자.

const Person = function (name, height) {
  this.name = name;
  this.height = height;
  this.eye = 2;
};

Person.prototype.age = 50;

const person1 = new Person("eunbin", 200);

<현재 person1 객체의 속성 현황>

 

person1의 상속받은 속성들은 모두 Person.prototype 객체에서 상속받은 속성들이다.

 

이 중 직접 지정해준 age속성은 열거 가능하지만 그 외의 constructor, __proto__( [[proto]] )속성은 열거 불가능하다.

 

 

1) for ... in 구문을 통해 열거가능하고 상속받은 속성을 포함하는 속성을 순회할 수 있다.

 

for (const key in person1) {
  console.log(key);
}

 

2) Object.keys 메서드를 이용해 열거가능하고 상속받은 속성을 제외하는 속성의 키값의 배열을 받을 수 있다.

Object.keys(person1);

 

- Object.getOwnPropertyDescriptor() 메소드를 이용하면 객체의 속성을 확인할 수 있다.

 

person1 객체 내부의 name 속성을 확인해보자.

Object.getOwnPropertyDescriptor(person1, "name"); 

 

Object.defineProperty는 속성의 정의를 수정할 수 있는 메서드이다.

 

이 메소드를 이용해 name의 enumerable을 false로 바꿔보자.

 

Object.defineProperty(person1, "name", {
  enumerable: false
});

<현재 person1 객체의 속성 현황>

 

3) Object.getOwnPropertyNames를 이용하면 객체 자신이 소유하는 속성의 키값의 배열을 받을 수 있다. (열거 가능, 불가능 모두 포함)

Object.getOwnPropertyNames(person1);

 

▶ 객체 자신이 소유하면서 열거가능한 속성의 키값이 필요할 땐 Object.key

▶ 객체 자신이 소유하면서 열거가능하고 열거 불가능한 속성 모두를 포함하는 키값이 필요할 땐 Object.getOwnPropertyNames

객체 자신이 소유하고 상속받은 속성까지 포함하는 열거 가능한 속성을 순회하려할 땐 for ... in 구문

 

▶ 객체 자신이 소유하고 열거가능한 속성만을 순회하려할 땐 for ... in 구문hasOwnProperty 로 판별

for (const key in person1) {
  if (person1.hasOwnProperty(key)) {
    console.log(key);  
  }
}

 

 

developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties

 

Enumerability and ownership of properties - JavaScript | MDN

Enumerability and ownership of properties Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Properties defined via Obj

developer.mozilla.org