好记性不如烂笔记:),简单的区分一下两者
typeof操作符用于判断变量的数据类型,使用typeof会有六种可能的返回:
- string、number、boolean、undefined、object、function
- js的数据类型中简单类型有String、Number、Boolean、Undefined、NULL五种,复杂类型有Object,使用typeof对Object和NULL类型检测都会返回object
- 使用typeof返回undefined可能存在两种情况:变量未申明、变量申明了但未初始化。e.g.
typeof(aa);//undefined
以及var aa;typeof(aa);//undefined
所以,显示的初始化变量是明智的,当typeof操作符返回”undefined”值时,说明变量还没有被声明 - 函数在ECMAScript中是对象,不是一种数据类型
instanceof用于判断某一变量是否是某个对象的实例,instanceof返回的是true/false
- 在后面的面向对象中讲到的instance也可以判断某一对象是否是某一原型对象的实例e.g.
alert(person instanceof Person);
- 对于类型检测问题,typeof适用于对基本类型的检测,而instanceof适用于对复杂类型检测(具体的引用类型值):
举栗子:
alert(person instanceof Object);
alert(colors instanceof Array);
alert(pattern instanceof RegExp);