hasOwnProperty란?
hasOwnProperty() 는 객체가 특정 프로퍼티를 가지고 있는지를 알려주는 메소드이다.
사용법은 객체.hasOwnProperty(’확인할 프로퍼티’)이고, 리턴되는 값은 **boolean**이다.
const object1 = {};
object1.property1 = 123;
console.log(object1.hasOwnProperty('property1')) // true
console.log(object1.hasOwnProperty('property2')) // false
object1이라는 객체를 만들고, 그 후에 property1이라는 프로퍼티에 123을 담았다. hasOwnPropery를 이용해 콘솔을 찍어 property1이 있는지 체크해보면 true가 나오고, property2라는 프로퍼티는 없기 때문에 false가 나온다.
반복문에서 사용해보기
var goods = {
displayName: 'phone case',
price: 1000,
};
for (var name in goods) {
if (goods.hasOwnProperty(name)) {
console.log(`goods안 프로퍼티 존재: ${name}`);
}
else {
console.log(`${name}프로퍼티는 없습니다.`);
}
}
goods안 프로퍼티 존재: displayName
goods안 프로퍼티 존재: price
주의할점 ! 만약 프로퍼티 이름으로 hasOwnProperty를 사용한다면?
javascript는 프로퍼티 명칭으로서 hasOwnProperty를 보호하지 않습니다. 사용하지 않도록합니다.
var goods = {
hasOwnProperty: 'test',
price: 10000
};
//케이스 1
goods.hasOwnProperty('price'); //오류발생
//케이스 1-1
goods.hasOwnProperty('hasOwnProperty'); //오류발생
//케이스2
({}).hasOwnProperty.call(goods, 'price'); //true
//케이스3
Object.prototype.hasOwnProperty.call(goods, 'price') //true
goods에 hasOwnProperty와 price라는 프로퍼티 명칭을 사용하여 각각 값을 넣고, 밑에서 케이스1처럼 price라는 프로퍼티가 있는지 확인해보면 hasOwnProperty가 함수가 아닌 키 값이 되었으므로 오류가 발생한다.
혹시나 싶어 케이스 1-1 처럼 hasOwnProperty라는 프로퍼티가 있는지 체크해보아도 오류가 나는걸로 보아 이미 goods 객체의 hasOwnProperty는 재선언 되었다는 것을 알 수 있다.
따라서, 해당 객체의 hasOwnProperty가 재선언되었을 수도 있기때문에 케이스 2, 3처럼 새로운 객체를 생성하여 사용하는 것이 좋다.
여기서, 자주 비교되는 hasOwn, in이란?
var person = {
name: '홍길동',
age: 20,
}
console.log('age' in person); //true
console.log(Object.hasOwn(person, 'age')); //true
console.log(person.hasOwnProperty('age')); //true
이렇게만 보면 ‘key’ in obj와 hasOwn, hasOwnProperty의 차이가 없어보인다. 하지만 아래 예시를 통해 다른것을 알 수 있다.
console.log('constructor' in person); //true
console.log(Object.hasOwn(person, 'constructor')); //false
console.log(person.hasOwnProperty('constructor')); //false
console.log(Object.prototype.hasOwnProperty.call(person, 'constructor')) //false
상속된 속성의 경우 in 연산자가 true를 반환하는 반면에, Object.hasOwn() 이나 Object.prototype.hasOwnProperty() 은 false를 반환하는 것을 확인할 수 있다.
in은 해당 객체의 prototype chain 까지 포함한 모든 객체 키를 조회하지만, hasOwn과 hasOwnProperty는 상속된 속성을 무시하고 자신이 가지고 있는 키값만 확인하는 것을 알 수 있다. (아래 이미지 참고)
정리
요약하자면, in연산자는 상속된 속성을 찾을 수 있지만 hasOwn과 hasOwnProperty는 찾을 수 없습니다.
'프론트엔드' 카테고리의 다른 글
vue router 네비게이션 가드 (0) | 2022.11.17 |
---|---|
React vs Vue (0) | 2022.11.17 |
Prototype 프로토타입 (0) | 2022.11.04 |
new 연산자 (0) | 2022.11.04 |
Closure 클로져 (0) | 2022.11.04 |