type:of 와 instanceof 소개 및 용법

7759 단어 instanceof
typeof
사용 방법:type:of a 또는 type:of(a)는 string 형식의 값 을 되 돌려 줍 니 다.
말 그대로 이 물건 은 검사 유형 입 니 다.출력 한 것 은 string 값 입 니 다.아래 의 검 측 코드 를 직접 보 세 요.
console.log(typeof 'i am a string');  // string                         

console.log(typeof true); // boolean

console.log(typeof 10); // number

console.log(typeof undefined);  // undefined

console.log(typeof function() {});  // function

console.log(typeof null); // object

console.log(typeof new String('i am a string')); // object

console.log(typeof new Boolean(true)); // object

console.log(typeof new Number(10)); // object

console.log(typeof [1, 2, 3, 4]); // object

console.log(typeof new Array(1, 2, 3, 4)); // object

console.log(typeof new Date()); // object

console.log(typeof new RegExp('hello world', 'g')); // object

console.log(typeof /hello/g); // object

이 물건 의 가장 큰 단판 은 null 과 배열 의 검 측 에 불리 합 니 다(모두 object 로 돌아 갈 수 있 습 니 다)!
type of 는 변수의 유형 을 초보 적 으로 검사 할 수 있 는 것 외 에 하나의 변수 가 비어 있 는 지 판단 할 수 있 습 니 다(할당 되 지 않 았 거나 설명 되 지 않 았 음).
var a;

if(typeof a === 'undefined') {  

  console.log('hello'); // hello

}



if(a === undefined) {

  console.log('world')  // world

}

재 미 있 는 것 은 할당 되 지 않 은 요소 와 type:of 연산 을 통 해 얻 은 결과 와 마찬가지 로"undefined"문자열 입 니 다(원래 type:of undefined 이기 때 문 입 니 다).
var a;

console.log(typeof a === typeof b); // true

이 때 는 어떻게 구별 해 야 합 니까?in window 로 판단 가능:
var a;

console.log('a' in window); // true

console.log('b' in window); // false

instanceof 에 비해 type:of 는 간단 합 니 다~
 instanceof
사용 방법:a instanceof b 에서 boolean 값 을 되 돌려 줍 니 다.
instanceof 의 영문 해석 은 인 스 턴 스 입 니 다.그 역할 은 특정한 변수 가 특정한 대상 인지 아 닌 지 를 판단 하 는 인 스 턴 스 입 니 다.검사 코드 보기:
console.log('string' instanceof String);  // false

console.log(true instanceof Boolean); // false

console.log(10 instanceof Number);  // false

console.log(undefined instanceof Object); // false

console.log(null instanceof Object);  // false



console.log({} instanceof Object);  // true

console.log(new String('string') instanceof String); // true

console.log(new Boolean(true) instanceof Boolean); // true

console.log(new Number(10) instanceof Number); // true

console.log([] instanceof Array); // true

console.log(new Array() instanceof Array); // true

console.log(new Date() instanceof Date); // true

console.log(new RegExp('') instanceof RegExp); // true

console.log(/hello/ instanceof RegExp); // true

 인 스 턴 스 of 는 기본 데이터 형식(예 를 들 어'string',true,10 등)을 대상 의 인 스 턴 스 라 고 할 수 없고 new 는 일반적으로 계산 하 는 것 을 볼 수 있다.
instanceof 의 첫 번 째 값(즉 a instanceof b 의 a)은 먼저 성명 을 해 야 합 니 다.그렇지 않 으 면 잘못 보고 해 야 합 니 다.type:of 는 성명 되 지 않 은 변 수 를 판단 할 수 있 습 니 다("undefined"로 되 돌아 갑 니 다).
 

좋은 웹페이지 즐겨찾기