hasOwnProperty vs prototype.hasOwnProperty
· 약 2분
for-in 구문을 쓸 때 상속된 프로퍼티나 this 구문을 방지하기 위하여 보통 hasOwnProperty 로 체크한다.
for (prop in obj) {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(prop)) {
// code...
}
}
문제점
위와 같은 방식은 아래와 같이 hasOwnProperty 가 재정의 된 객체에서 오류를 발생할 수 있다.
소스
const obj = {
hasOwnProperty: function () {
return false;
},
data1: 1,
};
for (prop in obj) {
// obj.hasOwnProperty(prop) 의 결과는 항상 false
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(prop)) {
// 이 구문은 실행되지 않는다.
}
}
prototype.hasOwnProperty
따라서 prototype 을 사용해 코딩해야한다.