객체에 속성이 있는지 확인 주의할 오류들
JavaScript에서 hasOwnProperty
사용법
JavaScript에서 객체가 특정 속성을 가지고 있는지 확인하기 위해 hasOwnProperty
메소드를 자주 사용합니다. 이 메소드는 객체에 지정된 이름의 속성이 있는지 여부를 불린 값으로 반환합니다.
1
2
3
const obj = { key: 'value' };
console.log(obj.hasOwnProperty('key')); // 출력: true
console.log(obj.hasOwnProperty('otherKey')); // 출력: false
하지만, hasOwnProperty
를 사용할 때 주의해야 할 몇 가지 오류가 있습니다.
TypeError: Cannot read property ‘hasOwnProperty’ of null
가장 흔하게 발생하는 오류 중 하나는 TypeError: Cannot read property 'hasOwnProperty' of null
입니다. 이 오류는 객체가 null
또는 undefined
일 때 발생합니다. 이를 방지하기 위해서는 객체가 존재하는지 먼저 확인해야 합니다.
1
2
3
if (obj && obj.hasOwnProperty('key')) {
// 코드 실행
}
hasOwnProperty가 없는 객체
또 다른 문제는 Object.create(null)
로 생성된 객체에는 hasOwnProperty
메소드가 없다는 것입니다.
1
2
const obj = Object.create(null);
console.log(obj.hasOwnProperty); // 출력: undefined
이 경우, Object.prototype.hasOwnProperty.call(obj, 'key')
와 같이 사용해야 합니다.
정리
- 객체가
null
또는undefined
일 경우,TypeError: Cannot read property 'hasOwnProperty' of null
오류가 발생합니다. Object.create(null)
로 생성된 객체에는hasOwnProperty
메소드가 없습니다.
이러한 오류를 피하려면 객체가 존재하는지 확인하고, 필요한 경우 Object.prototype.hasOwnProperty
를 사용하세요. 이렇게 하면 코드가 더 안정적이고 예측 가능해집니다.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.