Object.hasOwn(instance, prop)
-> return true / false// Object.prototype.hasOwnProperty()
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1')); // true
console.log(object1.hasOwnProperty('toString')); // false
console.log(object1.hasOwnProperty('hasOwnProperty')); // false
// Object.hasOwn()
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop')); // true
console.log(Object.hasOwn(object1, 'toString')); // false
console.log(Object.hasOwn(object1, 'undeclaredPropertyValue')); // false
이전에는 Object.prototype.hasOwnProperty() 로 객체가 특정 속성을 지니고 있는지 확인하였습니다.
prototype 상속이 이루어지기때문에 편하게 사용이 가능하지만 문제도 존재를 합니다.
오버라이딩을 하는 경우 또는 Object.create() 로 객체를 생성하는 경우에는 문제가 발생을 합니다.
오버라이딩을 하는 경우에는 Object.prototype.hasOwnProperty() 에 접근하기 전에 중복되는 속성으로 인해 가려집니다.
let obj = Object.create(null);
obj.name = "Object.create(null) 로 생성하면 Object.prototype 을 상속받지 않습니다.";
console.log("name" in obj); // true
console.log(Object.getPrototypeOf(obj)); // null
obj.hasOwnProperty("name"); // Uncaught TypeError: obj.hasOwnProperty is not a function
Object.hasOwn() 은 위 문제들에 대해서 회피가 가능합니다.(Object 생성자 함수에 속성으로 작성이 되었기 때문)
이미 대부분의 브라우저에서 지원을 한다.