What is the difference between typeof and instanceof?

1, typeof

typeof   The operator returns a string representing the type of the uncomputed operand

The method of use is as follows:

typeof operand

operand is an expression that represents an object or original value, and its type will be returned

for instance

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'

From the above example, the first six are basic data types. Although typeof null is object, this is only JavaScript   A long history of existence   Bug does not mean null is a reference data type, and null itself is not an object

So, null in   The returned result after typeof is the problematic result, which cannot be used as a method to judge null. If you need to   if   Determine whether it is   Null, just judge directly by = = = null

At the same time, you can find the reference type data. If you use typeof to judge, except function will be recognized, the rest will output object

If we want to judge whether a variable exists, we can use typeof: (if(a) cannot be used. If a is not declared, an error will be reported.)

if(typeof a != 'undefined'){
    //Variable exists

2, instanceof

instanceof   Operator is used to detect the of the constructor   prototype   Property appears on the prototype chain of an instance object

Use the following:

object instanceof constructor

Object is an instance object and constructor is a constructor

The constructor can instance the object through new, and instanceof can judge whether the object is the object generated by the previous constructor

//  Define build function
let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false

For the implementation principle of instanceof, please refer to the following:

function myInstanceof(left, right) {
    //  Here, use typeof to judge the basic data type. If yes, return false directly
    if(typeof left !== 'object' || left === null) return false;
    //  getProtypeOf is the API of the Object object Object, which can get the prototype Object of the parameter
    let proto = Object.getPrototypeOf(left);
    while(true) {                  
        if(proto === null) return false;
        if(proto === right.prototype) return true;//If the same prototype object is found, return true
        proto = Object.getPrototypeof(proto);

That is, follow the prototype chain until the same prototype object is found, and return true. Otherwise, it is false

3, Distinction

typeof and instanceof are both methods for judging data types. The differences are as follows:

  • typeof returns the basic type of a variable, and instanceof returns a Boolean value

  • instanceof   Complex reference data types can be accurately judged, but basic data types cannot be correctly judged

  • And typeof   It also has disadvantages, although it can judge the basic data type (null   Except function), but in the reference data type, except function   Other than the type, others cannot be judged

It can be seen that the above two methods have disadvantages and can not meet the needs of all scenarios

If you need a general detection data type, you can use Object.prototype.toString to call this method to uniformly return the string in the format "[object Xxx]"

as follows

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  //  The result is the same as above. It is ok to add call
Object.prototype.toString.call(1)    // "[object Number]"
Object.prototype.toString.call('1')  // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(null)   //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g)    //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([])       //"[object Array]"
Object.prototype.toString.call(document)  //"[object HTMLDocument]"
Object.prototype.toString.call(window)   //"[object Window]"

After understanding the basic usage of toString, let's implement a global data type judgment method

function getType(obj){
  let type  = typeof obj;
  if (type !== "object") {    //  Type of judgment is performed first. If it is a basic data type, it is returned directly
    return type;
  //  If the return result of typeof is object, make the following judgment to return the regular result
  return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1'); 

Use the following

getType([])     //  "Array"   typeof   [] is an object, so toString returns
getType('123')  //  "string"   typeof   Direct return
getType(window) //  "Window"   toString return
getType(null)   //  "null" initial capital, typeof "   null is an object, which needs toString to judge
getType(undefined)   //  "undefined"   typeof   Direct return
getType()            //  "undefined"   typeof   Direct return
getType(function(){}) //  "function"   typeof can judge, so the first letter is lowercase
getType(/123/g)      //"RegExp"   toString return

Tags: Javascript

Posted on Mon, 18 Oct 2021 20:49:56 -0400 by amcgrath