[TIL] hasOwnProperty vs in 연산자

Outclass·2022년 7월 13일
0

어떤 객체의 property를 확인하는 메소드로는 hasOwnProperty와 in 연산자가 있다. 둘다 객체의 키가 존재하는지를 확인한후 boolean을 리턴한다


const obj = {a:1, b:2, c:3}

//hasOwnProperty
obj.hasOwnProperty("a") // returns true
obj.hasOwnProperty("test") // returns flase

//in 연산자
"a" in obj // returns true 
"test" in obj // returns false

그렇다면 차이는 없을까. 같은 역할을 하는 두가지 방식이 존재할 때에는 분명 차이도 있을 것 같다. 차이에 대한 MDN의 설명이다.

모든 객체는 hasOwnProperty 를 상속하는 Object의 자식이다. 이 메소드는 객체가 특정 프로퍼티를 자기만의 직접적인 프로퍼티로서 소유하고 있는지를 판단하는데 사용된다. in 연산과는 다르게, 이 메소드는 객체의 프로토타입 체인을 확인하지는 않는다. - MDN

obj = new Object();
obj.prop = 'exists';

//in
'prop' in obj;             // returns true
'toString' in obj;         // returns true
'hasOwnProperty' in obj;   // returns true

//hasOwnProperty
obj.hasOwnProperty('prop');             // returns true
obj.hasOwnProperty('toString');         // returns false
obj.hasOwnProperty('hasOwnProperty');   // returns false
  • 위의 예시처럼 in의 경우 obj가 가진 property만이 아닌 prototype체인을 확인해서 boolean을 리턴하는 반면
  • hasOwnProperty의 경우 toString이나 hasOwnProperty는 obj가 자체적으로 가진 property가 아니므로 false를 리턴하게 된다

참고링크 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

profile
When you stop having big dreams that’s when you’ve died, despite not being buried yet.

0개의 댓글