✔모던 자바스크립트 13장
참고 - https://poiemaweb.com/
타입체크
- 자바스크립트는 동적타입의 언어이므로 변수에 어떤 값이 할당될 지 예측하기 어렵다.
function sum(a, b) {
return a + b;
}
function sum(a, b) {
return a + b;
}
sum('x', 'y');
typeof
typeof '';
typeof 1;
typeof NaN;
typeof true;
typeof [];
typeof {};
typeof new String();
typeof new Date();
typeof /test/gi;
typeof function () {};
typeof undefined;
typeof null;
typeof undeclared;
typeof
연산자는 null과 배열의 경우 object, 함수의 경우 function를 반환하고, Date, RegExp, 사용자 정의 객체 등 거의 모든 객체의 경우, object를 반환한다.
따라서 typeof
는 null을 제외한 원시 타입을 체크하는 데는 문제가 없지만 객체의 종류까지 구분하여 체크하려할 때는 사용하기는 곤란하다.
Object.prototype.toString
var obj = new Object();
obj.toString();
function getType(target) {
return Object.prototype.toString.call(target).slice(8, -1);
}
instanceof
- 타입 연산자(Type Operator)에는 앞서 살펴본
typeof
이외에 instanceof
를 제공한다.
instanceof 연산자는 피연산자인 객체가 우항에 명시한 타입의 인스턴스인지 여부를 알려준다.
이때 타입이란 constructor를 말하며 프로토타입 체인에 존재하는 모든 constructor를 검색하여 일치하는 constructor가 있다면 true를 반환한다.
function Person() {}
const person = new Person();
console.log(person instanceof Person);
console.log(person instanceof Object);
유사배열객체
- 유사 배열 객체(array-like object)은 length 프로퍼티를 갖는 객체로 문자열, arguments, HTMLCollection, NodeList 등은 유사 배열이다. 유사 배열 객체는 length 프로퍼티가 있으므로 순회할 수 있으며 call, apply 함수를 사용하여 배열의 메소드를 사용할 수도 있다.
- 어떤 객체가 유사 배열인지 체크하려면 우선 length 프로퍼티를 갖는지 length 프로퍼티의 값이 정상적인 값인지 체크한다.
console.log(Array.isArray([]));
console.log(Array.isArray({}));
console.log(Array.isArray('123'));