자바스크립트는 동적 타입(dynamic typed) 언어이므로 변수에 어떤 값이 할당될 지 예측하기 어렵기 때문에 자바스크립트는 타입 체크가 필요하다.
1. typeof
타입 연산자(Type Operator) typeof
는 피연산자의 데이터 타입을 문자열로 반환한다.
※ typeof
연산자는 null과 배열의 경우 object, 함수의 경우 function를 반환하고, Date, RegExp, 사용자 정의 객체 등 거의 모든 객체의 경우, object를 반환한다. 객체의 종류까지 구분할 수 없다.
typeof ''; // string
typeof 1; // number
typeof NaN; // number
typeof true; // boolean
typeof []; // object
typeof {}; // object
typeof new String(); // object
typeof new Date(); // object
typeof /test/gi; // object
typeof function () {}; // function
typeof undefined; // undefined
typeof null; // object (설계적 결함)
typeof undeclared; // undefined (설계적 결함)
2. Object.prototype.toString
Object.prototype.toString 메소드는 객체를 나타내는 문자열을 반환한다.
var obj = new Object();
obj.toString(); // [object Object]
Function.prototype.call 메소드를 사용하면 모든 타입의 값의 타입을 알아낼 수 있다.
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(new String()); // [object String]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(new Number()); // [object Number]
Object.prototype.toString.call(NaN); // [object Number]
Object.prototype.toString.call(Infinity); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(Math); // [object Math]
Object.prototype.toString.call(/test/i); // [object RegExp]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(document); // [object HTMLDocument]
Object.prototype.toString.call(argument); // [object Arguments]
Object.prototype.toString.call(undeclared); // ReferenceError
3. instanceof
instanceof 연산자는 피연산자인 객체가 우항에 명시한 타입의 인스턴스인지 여부를 알려준다. 이때 타입이란 constructor를 말하며 프로토타입 체인에 존재하는 모든 constructor를 검색하여 일치하는*constructor가 있다면 true를 반환한다.
function Person() {}
const person = new Person();
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
참고
'JS > JS 공부는 다다익선 [모던자바스크립트]' 카테고리의 다른 글
JS 공부는 다다익선 - 8. 스코프(Scope) (0) | 2023.09.22 |
---|---|
JS 공부는 다다익선 - 7. prototype (0) | 2023.09.21 |
JS 공부는 다다익선 - 5. 함수(Function) (0) | 2023.09.21 |
JS 공부는 다다익선 - 4. 객체(Object) (0) | 2023.09.20 |
JS 공부는 다다익선 - 3. 변수 (0) | 2023.09.20 |