Object.prototype.hasOwnProperty()
hasOwnProperty() 메소드는 객체
가 특정 프로퍼티
를 가지고 있는지를 나타내는 boolean 값(true
or false
)을 반환한다. 다음은 hasOwnProperty()와 비슷한 방법들을 예시를 들어서 표현해 보았다.
const market = {
fruits: "apple",
employee: "Mike",
};
console.log(market.hasOwnProperty("fruits"));
console.log(Object.hasOwn(market,"employee"));
console.log("employee" in market);
console.log(Object.prototype.hasOwnProperty.call(market,"employee"));
true
true
true
true
이 함수를 활용하여 특정 프로퍼티
를 객체
가 갖고 있는지 여부를 확인하여 원하는 로직을 짤 수가 있다.
자바스크립트는 hasOwnProperty를 변수명으로 사용하였을 경우에 보호해주지 못한다.
const market = {
hasOwnProperty : function () {
return false;
},
fruits: "apple",
employee: "Json",
};
즉 객체에 프로퍼티명으로 hasOwnProperty를 설정하였을 경우에 hasOwnProperty 메소드의 기능을 상실한다. 그럴땐 아래와 같은 함수로 대체할 수 있다.
console.log(Object.hasOwn(market, "employee"));
console.log(Object.prototype.hasOwnProperty.call(market,"employee"));
true
true