
프로퍼티가 객체에 직접 속해있는지 확인하는 hasOwnProperty 메서드는 매우 유용하지만, 안전하게 사용하기 위해서는 몇 가지 주의사항이 있다.
const person = {
name: 'junhee'
};
person.hasOwnProperty('name'); // true
person.hasOwnProperty('age'); // false
단순해 보이지만, 여기에는 큰 문제가 있다
자바스크립트는 hasOwnProperty라는 이름을 특별히 보호하지 않는다. 따라서 누군가 이 메서드를 덮어쓸 수 있다.
const foo = {
hasOwnProperty: function() {
return 'hasOwnProperty'; // 😱 원래 기능이 사라짐
},
bar: 'string'
};
// ❌ 의도한 대로 동작하지 않음
foo.hasOwnProperty('bar'); // 'hasOwnProperty'
// ✅ 안전한 방법
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
function hasOwnProp(targetObj, targetProp) {
return Object.prototype.hasOwnProperty.call(targetObj, targetProp);
}
// 사용 예시
hasOwnProp(foo, 'bar'); // true
function hasOwnProp(targetObj, targetProp) {
return Object.prototype.hasOwnProperty.call(targetObj, targetProp);
}
// ✅ for...in 루프에서 안전하게 사용
const object = {
a: 1,
b: 2
};
for (const key in object) {
if (hasOwnProp(object, key)) {
console.log(`${key}: ${object[key]}`);
}
hasOwnProperty는 유용하지만 덮어쓰기가 가능한 위험이 있음Object.prototype.hasOwnProperty.call을 사용하면 안전for...in 루프에서 유용하게 활용 가능