갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • prototype
  • Arrow
  • symbol
  • 객체타입
  • 원시타입
  • 함수
  • class
  • 렉시컬 환경
  • 컴파일러
  • 스코프 체인
  • 호이스팅
  • ECMAScript
  • nodemon
  • 싱글스레드
  • 정적 레벨
  • Babel
  • PM2
  • 상속
  • SPREAD
  • function
  • 네이밍
  • 오버라이딩
  • 인터프리터
  • 이터러블
  • this
  • 심볼
  • structure
  • 프로토타입
  • 실행 컨텍스트
  • 자바스크립트엔진

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

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
  • 알아두면 좋은 지식이다. (사실 이렇게까지 안해도 된다.)

'Study > JavaScript(Clean code)' 카테고리의 다른 글

[JavaScript][clean-code] 함수, 메서드, 생성자  (0) 2022.06.09
[JavaScript][clean-code] 직접 접근 지양하기  (0) 2022.06.09
[JavaScript][clean-code] Prototype 조작 지양하기  (0) 2022.06.07
[JavaScript][clean-code] Object.freeze  (0) 2022.06.07
[JavaScript][clean-code] Object Destructuring (객체 구조 분해 할당)  (0) 2022.06.07
    'Study/JavaScript(Clean code)' 카테고리의 다른 글
    • [JavaScript][clean-code] 함수, 메서드, 생성자
    • [JavaScript][clean-code] 직접 접근 지양하기
    • [JavaScript][clean-code] Prototype 조작 지양하기
    • [JavaScript][clean-code] Object.freeze
    갈푸라떼
    갈푸라떼

    티스토리툴바