关于JavaScript中的类型判断,我想大部分JavaScripter 都很清楚 typeof 和  instanceof,却很少有人知道 constructor,以及constructor与前面二者的关系

typeof

console.log(typeof 1); //number
console.log(typeof "宋远溪"); // string
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof Symbol(1)); //symbol
console.log(typeof null);//object
console.log(typeof undefined); // undefined
console.log(typeof BigInt(1)); //bigint, ES10推出的BigInt是一个内置对象,它提供了表示大于最大安全整数之外的方法, bigint 通常用于计算最大安全整数之外的数值

如你所见,typeof只能进行最基本的类型判断;那我们如果想知道一个变量是对象或者是数组怎么办?接下来

instanceof

console.log ({} instanceof Object); // true
console.log ([] instanceof Array); // true
function Something () {}
var sth = new Something();
console.log(sth instanceof Something); // true

可以看到 instanceof 能区分出数据的类型,以及该数据是由谁创建的,但是,instanceof 就真的万无一失吗?继续往下

function Something () {}
function Anything() {}
Something.prototype = new Anything();
var sth = new Something();
console.log(sth instanceof Something);//true
console.log(sth instanceof Anything);//true

为什么会这样?

因为instanceof 会检查 Anything 是否 存在与 sth 的原型链上,如果存在,则返回True,这么说的话,下面的也是成立的

console.log(sth instanceof Object); //true

constructor

function Something() {}
function Anything() {} var template = new Anything();
template.constructor = Something;
Object.defineProperty(template,'constructor',{
enumerable:false,
writable:false,
});
Something.prototype = template; const sth = new Something(); console.log(sth.constructor === Something);//true
console.log(sth.constructor === Anything);//false
console.log(Object.keys(sth)); // [],因为constructor属于内置属性,所以我们配置不可枚举,不可重写;
sth.constructor 其实就是 sth.__proto__.constructor,因为constructor属性存在于原型链上,所以我们可以直接简写;这样就能实现精确1对1比对了

最新文章

  1. oracle xmltype导入并解析Excel数据 (五)中间表数据入库
  2. 从键盘上输入一个正整数n,请按照以下五行杨辉三角形的显示方式, 输出杨辉三角形的前n行。请采用循环控制语句来实现。
  3. Linux 性能优化之 IO 子系统
  4. centos设置编码
  5. GitHub指南
  6. 网站添加到IIS和附件进程调试(新手使用篇)
  7. hdu 5427 A problem of sorting 水题
  8. HW2.17
  9. 安卓Menu键的问题
  10. JavaScript数组知识网络
  11. [记录]Zabbix3.4配置监控Oracle12c的存活状态和表空间使用率
  12. HttpServletRequest对象方法的用法
  13. Linux编程学习笔记(一)
  14. 1.2.3 Excel中姓名处理,将名加密星号
  15. Java - 29 Java 序列化
  16. Git从零开始(二)
  17. msc文件
  18. Python中字典的基本操作
  19. Print Nodes in Top View of Binary Tree
  20. iOS-夜间模式(换肤设置)

热门文章

  1. IOC技术在前端项目中的应用
  2. 10_1_OS模块
  3. Django-html文件实例
  4. 浅析Asp.Net Core框架IConfiguration配置
  5. http 和 https 有何区别?如何灵活使用?
  6. OAuth2.0与前端无感知token刷新实现
  7. js--数组的find()和findIndex()方法的使用介绍
  8. (十七)整合 Zookeeper组件,管理架构中服务协调
  9. Java中String对象创建机制详解()
  10. 深入理解java虚拟机,GC参考手册