⭐ ⭐

Difficulty ratings range from five stars to one star.

A:

Use Object. The prototype. ToString method, can accurately determine the data type.

Disadvantages of Typeof and Instanceof

  •  typeofIt can be judged that in additionnullOther than the underlying data type, but when determining the reference type, exceptfunctionType, others can not be accurately determined.
  • instanceofYou can accurately determine the various reference types, but not the raw data types.

Object.prototype.toString

Calling this method returns a string of the format [Object Xxx] to represent the object.

// Call directly
Object.prototype.toString({})      // '[object Object]'

/ / plus the call
// Reference type
Object.prototype.toString.call({})           // '[object Object]'
Object.prototype.toString.call(function(){}) // "[object Function]'
Object.prototype.toString.call(/123/g)       // '[object RegExp]'
Object.prototype.toString.call(new Date())   // '[object Date]'
Object.prototype.toString.call(new Error())  // '[object Error]'
Object.prototype.toString.call([])           // '[object Array]'
Object.prototype.toString.call(new Map())    // '[object Map]'
Object.prototype.toString.call(new Set())    // '[object Set]'
Object.prototype.toString.call(new WeakMap()) // '[object WeakMap]'
Object.prototype.toString.call(new WeakSet()) // '[object WeakSet]'
Object.prototype.toString.call(document)     // '[object HTMLDocument]'
Object.prototype.toString.call(window)       // '[object Window]'
Object.prototype.toString.call(this)         // '[object Window]'

// Primitive type
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(1n)          // '[object BigInt]'
Object.prototype.toString.call(null)        // '[object Null]'
Object.prototype.toString.call(undefined)   // '[object Undefined]'
Object.prototype.toString.call(Symbol('a')) // '[object Symbol]'

Copy the code

Why call

Call is a function method that changes the reference to this, or apply.

If we don’t change this to our target variable, this will always point to calling Object.prototype.

Object.prototype.toString([])       // '[object object]' this refers to object. prototype.
Object.prototype.toString.call([])  // '[object Array]'
Copy the code
/ / overridable Object. The prototype. The toString method, print this look
Object.prototype.toString = function ({
  console.log(this)}// Reference type
Object.prototype.toString([])       // Object.prototype
Object.prototype.toString.call([])  / / []

// Primitive type
Object.prototype.toString(1)       // Object.prototype
Object.prototype.toString.call(1)  // Number {1}
// Number {1} is a wrapper class that wraps basic types around their corresponding reference types, giving them the properties of objects
Copy the code

Encapsulate a utility function that accurately determines the type

Object. The prototype. ToString judgment types of defects

  • When determining the primitive typeThe operation using theProduce a lot ofTemporary objects

Although Object. The prototype. ToString can judge all types, but we can also combine typeof, from each director, wrap a precise judgment type tool function.

function getType (obj) {
  const type = typeof obj
  if(type ! = ='object') { // Check typeof first, if it is a basic data type, return directly
    return type
  }
  // If it is a reference type, then make the following judgment, the re returns the result
  return Object.prototype.toString
    .call(obj)
    .replace(/^\[object (\S+)\]$/.'$1')
    .toLocaleLowerCase()
}

getType(true)         // boolean
getType(1)            // number
getType('1')          // string
getType(1n)           // bigint
getType(null)         // null
getType(undefined)    // undefined
getType(Symbol('a'))  // symbol

getType([])            // array
getType({})            // object
getType(function() {}) // function
getType(new Date())    // date
getType(/abc/)         // regexp
getType(new Error())   // error
getType(document)      // htmldocument
getType(window)        // window

Copy the code

At the end

This is the 37th day of alynn’s blog post, exporting insight techniques. Goodbye

If my article is helpful to you, your 👍 is my biggest support ^_^