JavaScript에서 프리미티브 (부울, 널, 숫자, 문자열 및 값 undefined(및 ES6의 기호 ))를 제외한 모든 것이 오브젝트 (또는 최소한 오브젝트로 취급 될 수 있음)입니다.
console.log(typeof true); // boolean
console.log(typeof 0); // number
console.log(typeof ""); // string
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof function () {}); // function
보시다시피 객체, 배열 및 값 null은 모두 객체로 간주됩니다 ( null존재하지 않는 객체에 대한 참조입니다). 함수는 특별한 유형의 호출 가능한 객체 이기 때문에 구별 됩니다. 그러나 여전히 개체입니다.
반면에 리터럴은 true, 0, ""및 undefined하지 개체입니다. JavaScript에서 기본 값입니다. 그러나 부울, 숫자 및 문자열에는 constructor Boolean이 Number있고 String각각 추가 된 기능을 제공하기 위해 각각의 기본 요소를 랩핑합니다.
console.log(typeof new Boolean(true)); // object
console.log(typeof new Number(0)); // object
console.log(typeof new String("")); // object
당신은 원시 값이 내 포장 할 때 볼 수있는 것처럼 Boolean, Number그리고 String생성자 각각 그들은 개체가됩니다. instanceof연산자는 (은 반환 이유입니다 개체에 대한 작동 false기본 값) :
console.log(true instanceof Boolean); // false
console.log(0 instanceof Number); // false
console.log("" instanceof String); // false
console.log(new Boolean(true) instanceof Boolean); // true
console.log(new Number(0) instanceof Number); // true
console.log(new String("") instanceof String); // true
당신은 모두를 볼 수있는 typeof및 instanceof값이 부울, 숫자 또는 문자열인지 테스트에 불충분 한 - typeof단지 원시 논리 값, 숫자, 문자열 작동; 및 instanceof원시 논리 값, 숫자, 문자열이 작동하지 않습니다.
다행히이 문제에 대한 간단한 해결책이 있습니다. 의 기본 구현 toString(즉, 기본적으로 정의 된대로 Object.prototype.toString)은 [[Class]]기본 값과 객체 의 내부 속성을 반환 합니다.
function classOf(value) {
return Object.prototype.toString.call(value);
}
console.log(classOf(true)); // [object Boolean]
console.log(classOf(0)); // [object Number]
console.log(classOf("")); // [object String]
console.log(classOf(new Boolean(true))); // [object Boolean]
console.log(classOf(new Number(0))); // [object Number]
console.log(classOf(new String(""))); // [object String]
[[Class]]값 의 내부 속성은 값보다 훨씬 유용 typeof합니다. 우리는 다음과 같이 Object.prototype.toString자신의 (더 유용한) 버전의 typeof연산자 를 만드는 데 사용할 수 있습니다 .
function typeOf(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
console.log(typeOf(true)); // Boolean
console.log(typeOf(0)); // Number
console.log(typeOf("")); // String
console.log(typeOf(new Boolean(true))); // Boolean
console.log(typeOf(new Number(0))); // Number
console.log(typeOf(new String(""))); // String
이 기사가 도움이 되었기를 바랍니다. 프리미티브와 랩핑 된 객체의 차이점에 대한 자세한 내용은 다음 블로그 게시물을 참조하십시오. JavaScript 프리미티브의 비밀 생활