[JavaScript] The difference between typeof and instanceof in JS

The difference between typeof and instanceof in JS

Same point:

JavaScript, typeofand instanceofused to judge whether a variable is empty, or what type .

difference:

typeof:

  1. The return value is a string , used to describe the data type of the variable .
  2. typeofGenerally only a few returned the following results: number, boolean, string, function, object, undefined.
 if (typeof a != "undefined") {
    
    
   console.log("ok");

 } eles {
    
    
    console.log("not ok");
}
//下面的代码是错误的
// if (a) //因为如果 a 不存在( 未声明) 则会出错。

// if (a) {
    
    
//     console.log("ok");

// } else {
    
    
//     console.log('cc');

// }

For special objects such as Array and Null, using typeof will always return object, which is the limitation of typeof.

instanceof:

  1. The return value is 布尔值true / false;
  2. instanceofUsed to determine whether a variable belonging to an object of 实例.
// var a = new Array();
// alert(a instanceof Array); // true
// alert(a instanceof Object) // true

//如上, Array  object 的子类,所以结果都为true
// alert(b instanceof Array) // b is not defined

// function Test() {
    
    };
// var a = new test();
// alert(a instanceof test) // true

————————————————
Copyright statement: This article is the original article of the CSDN blogger "Mengli Mengyi", and it follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link for reprinting. And this statement.
Original link: https://blog.csdn.net/qq_38601916/article/details/81275091

Guess you like

Origin blog.csdn.net/iChangebaobao/article/details/106467699