Study/JavaScript(Clean code)

[JavaScript][clean-code] hasOwnProperty

갈푸라떼 2022. 6. 7. 16:42

* hasOwnProperty

- property를 가지고 있는가?

- 가지고있다면 true 없다면 false를 반환한다.

const person = {
  name : 'hyeonwoo'
}

person.hasOwnProperty(name); // true
person.hasOwnProperty(age); // false
  • JavaScript는 프로퍼티 명칭으로서 hasOwnProperty를 보호하지 않는다.
  • 그러므로 이 명칭을 사용하는 프로퍼티를 가지는 객체가 존재하려면 즉, 올바른 결과들을 얻기 위해서는
    외부 hasOwnProperty를 사용해야한다.
    • 아래의 예시를 통해 확인해보기

* 예시를 통한 확인 (hasOwnProperty)

// hasOwnProperty라는 메서드와 bar라는 문자열을 가지고 있는 foo
const foo = {
  hasOwnProperty: function() {
    return 'hasOwnProperty';
  },
  bar : 'string',
};

foo.hasOwnProperty('bar'); // hasOwnProperty
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
  • 마치 자바스크립트의 이슈와도 같은것이다.
  • hasOwnProperty는 보호를 받지 못한다. (prototype에 있기 때문에)
  • prototype에 접근하는것은 좋지 않지만 call()을 이용한 접근은 그나마 안전하다.

* 혹은 함수로 만들어서 편하게 사용하는 방법

function hasOwnProp(targetObj, targetProp) {
  return Object.prototype.hasOwnProperty.call(
    targetObj,
    targetProp,
  );
}

const person = {
  name : 'hyeonwoo'
}

hasOwnProp(person, 'name'); // true

const foo = {
  hasOwnProperty: function() {
    return 'hasOwnProperty';
  },
  bar : 'string',
};

hasOwnProp(foo, 'hasOwnProperty'); // true
  • 알아두면 좋은 지식이다. (사실 이렇게까지 안해도 된다.)