Determine the data type (constructor)

  • Original : MDN-constructor

  • Function : constructorReturns the reference of the Object constructor that created the instance object.

  • Description :

All objects inherit from a prototype on its constructorproperty.

const arr = [];
console.log(arr.constructor === Array); // true

const obj = {
    
    };
console.log(obj.constructor === Object); // true

const num = 1;
console.log(num.constructor === Number); // true

const str = '1';
console.log(str.constructor === String); // true

const bool = true;
console.log(bool.constructor === Boolean); // true

const nul = null;
// console.log(nul.constructor); // 报错:Uncaught TypeError: Cannot read property 'constructor' of null at <anonymous>:1:5

const undefin = undefined;
// console.log(undefin.constructor); // 报错:Uncaught TypeError: Cannot read property 'constructor' of null at <anonymous>:1:5
  • Description :

This we know, is through constructorto determine a type of data:

In this article, we will pass typeof, instanceof, constructorand Object.prototype.toString().call()these four methods, these methods to explain the situation to determine the type of data.

  • This document is quoted from Yu Diuyou – Liang Sir is also his own learning experience
  • Liang sirGit address: [https://github.com/LiangJunrong/document-library]

Guess you like

Origin blog.csdn.net/weixin_43956521/article/details/111469860