判断数据类型(constructor)

  • 原文MDN - constructor

  • 功能constructor 返回创建实例对象的 Object 构造函数的引用。

  • 描述

所有对象都会从它的原型上继承一个 constructor 属性。

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
  • 说明

本次我们了解的,是通过 constructor 来判断某个数据的类型:

在这篇文章中,我们会通过 typeofinstanceofconstructor 以及 Object.prototype.toString().call() 这四个方法,讲解这些方法判断数据类型的情况。

  • 本文档引自与掘友–梁sir 同时也是自己的学习经历
  • 梁sirGit地址:[https://github.com/LiangJunrong/document-library]

猜你喜欢

转载自blog.csdn.net/weixin_43956521/article/details/111469860