본문 바로가기

javascript

in vs hasOwnProperty

Q>
in과 hasOwnProperty를 이용하여 인스턴스에 해당 프러퍼티가 있는지 확인을 하려고 합니다.
이 둘의 차이점이 있나요?

 

A>
in 과 hasOwnProperty에는 차이점이 존재하고, 이에 따라 서로 다른 결과가 나타날 수 있습니다.
in의 경우 해당 객체의 인스턴스가 가지는 프러퍼티뿐만 아니라 프로토타입 체인(prototype chain)을 따라 올라가 객체가 가지는 (객체의 prototype에 정의 된) 프러퍼티까지 조회를 하게 됩니다.
이에 비해 hasOwnProperty의 경우 현재 생성된 객체의 인스턴스가 가지는 프러퍼티만 조회를 합니다.

예로,

function Foo(){
    this.name = 'hey';
}
TestObj.prototype.gender = 'male';

위와 같은 객체를 정의하고, 인스턴스를 생성하여 프러퍼티가 있는지 여부를 각각 in과 hasOwnProperty로 찍어보면,

var o = new Foo();
console.log(o.hasOwnProperty('name')); // true
console.log('name' in o); // true

console.log(o.hasOwnProperty('gender')); // false
console.log('gender' in o); // true

가 됩니다.

즉, 인스턴스의 프러퍼티가 아닌 prototype에 정의된 프러퍼티를 조회하려면 아래와 같이 해주면 됩니다.

console.log(('name' in o) && !o.hasOwnProperty('name')); //false
console.log(('gender' in o) && !o.hasOwnProperty('gender')); //true - prototype에 정의


'javascript' 카테고리의 다른 글

2016년에 자바스크립트를 배우는 기분  (0) 2016.10.10
== vs === 비교  (0) 2016.08.28
자바스크립트의 메모리관리  (0) 2016.08.16
Object.defineProperty  (0) 2016.08.16
자바스크립트 상속!! 후......ㅠ  (0) 2016.07.21