[PoimaWeb] 타입체크

hello__0·2022년 10월 7일
0

PoiemaWeb

목록 보기
4/5

instanceof

생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별한다.

생성된 함수의 첫번째 매개변수에는 HTMLElement를 상속받은 DOM요소가 전달되어야 한다.
이를 확인하기 위하여 instanceof를 사용한다.

DOM tree의 객체 구성

instanceof 연산자는 피연산자인 객체가 우항에 명시한 타입의 인스턴스인지 여부를 알려준다.
이때 타입이란 constructor를 말하며 프로토타입 체인에 존재하는 모든 constructor를 검색하여 일치하는 constructor가 있다면 true를 반환한다.

function Person() {}
const person = new Person();

console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// expected output: true

console.log(auto instanceof Object);
// expected output: true

만약 객체에 존재하지 않으면 not defined 가 출력된다.


유사 배열 객체

Array.isArray 메소드를 사용

특징

  • 유사 배열 객체(array-like object)은 length 프로퍼티를 갖는 객체이다.
  • 문자열, arguments, HTMLCollection, NodeList 등은 유사 배열이다.
  • 유사 배열 객체는 length 프로퍼티가 있으므로 순회할 수 있으며 call, apply 함수를 사용하여 배열의 메소드를 사용할 수도 있다.
  • index번호가 0번부터 시작해서 1씩증가해야한다.

어떤 객체가 유사 배열인지 체크하려면 우선 length 프로퍼티를 갖는지 length 프로퍼티의 값이 정상적인 값인지 체크해야 한다.

html

<body>
    <div id="outer">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
  </body>

js

let outer = document.querySelector("#outer");
console.log(outer);
console.log(typeof outer);
console.log(Array.isArray(outer));
console.log(outer instanceof Array);

output

profile
자라나라 나무나무

0개의 댓글