본문 바로가기
개발/javascript

19장 프로토타입 - hasOwnProperty, Object.create

by 올럭Dev 2023. 11. 28.
728x90

Object의 property가 있는지 확인하기 위해 .hasOwnProperty()를 사용합니다. Eslint를 사용하면 밑줄이 그어지는데, 그 원인을 알아 보겠습니다.
그리고 대안도 함께 알아 보겠습니다.

목차 📑

  • Object.create() 란?
  • 해결방법1
  • 해결방법2

Object.create() 란?

Object를 생성할 때, prototype을 인자로 받아 객체를 생성해주는 함수입니다. 즉 객체를 생성하면서 직접적으로 상속을 구현하는 것입니다.

장점은

  • new 연산자 없이도 객체를 생성할 수 있습니다.
  • 프로토타입을 지정하면서 객체를 생성할 수 있습니다.
  • 객체 리터럴에 의해 생성된 객체도 상속받을 수 있습니다.

obj.hasOwnProperty() 사용시 문제점

const obj1 = { a : 1 };
const obj2 = Object.create(null);
obj2.a = 2;

const hasOwnProperty1 = obj1.hasOwnProperty('a') // true
console.log(obj2.a); // a
const hasOwnProperty2 = obj2.hasOwnProperty('a') // obj2.hasOwnProperty is not a function

프로토타입 체인 종점에 위치하는 객체를 null로 생성할 수 있습니다.
그래서 Object.prototype의 빌트인 메서드(hasOwnProperty(), isPrototypeOf(), propertyIsEnumerable() 등 )를 사용할 수 없게 됩니다.
Object.prototype의 빌트인 메서드를 사용할 수 없는 경우가 생겨 Eslint에서 밑줄로 표시를 해주는 것입니다.

해결방법1

Object.prototype.hasOwnProperty.call(obj, property)

const obj2 = Object.create(null);
obj2.a = 2;
const hasOwnProperty =  Object.prototype.hasOwnProperty.call(obj2, 'a'); // true

Object.prototype의 빌트인 메서드를 간접적으로 호출합니다.

해결방법2

lodash의 Object 함수인 has()를 사용합니다.

const has = _.has(obj2, "a");
console.log("has : ", has);

추가 내용

마찬가지로 Object.prototype을 상속받지 않는 객체를 생성할 수도 있기 때문에 __proto__접근자 프로퍼티를 사용할 수 없는 경우가 있습니다.

// Object.__proto__를 상속받을 수 없습니다.
const obj = Object.create(null);

console.log(obj.__proto__) // undefined
console.log(Object.getPrototypeOf(obj)); // null

따라서 __proto__ 접근자 프로퍼티 대신 프로토타입의 참조를 취득하고 싶은 경우에는 Object.getProtoTypeOf()를 사용하고, 프로토타입을 교체하고 싶은 경우에는 Object.setProtoTypeOf()를 사용할 것을 권장한다고 합니다.

마치며 🍺

평소에 Eslint 자동 완성 주석으로 회피했었는데, 이번 기회에 원인과 해결 방법을 알아보았습니다.!
lodash에 has()와 hasIn()이 있는데, 이 부분의 차이도 나중에 한번 다루어 보겠습니다.~

함께하면 좋은 글 😍

728x90