ES2022 Object.hasOwn()

katanazero·2022년 3월 2일
0

etc

목록 보기
9/12

Object.hasOwn()

  • Object.prototype.hasOwnProperty() 를 대체하기 위해 등장
  • 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 생성자 함수에 속성으로 작성이 되었기 때문)


  • ES2022 에서 Object.prototype.hasOwnProperty() 를 대체하는 Object.hasOwn() 등장
  • hasOwnProperty() 는 이제 놔주고.. 새로운 아이를!!


이미 대부분의 브라우저에서 지원을 한다.

profile
developer life started : 2016.06.07 ~ 흔한 Front-end 개발자

0개의 댓글