数据类型,包含这7种: number、boolean、symbol、string、object、undefined、function
1、typeof
- 不能区分null、[]、{}
typeof "" string
typeof 1 number
typeof true boolean
typeof undefined undefined
typeof null object
typeof {} object
typeof [] object
typeof function(){} function
2、instanceof
- instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:
instanceof 检测的是原型
"1" instanceof String false
1 instanceof Number false
true instanceof Boolean false
{} instanceof Object true
[] instanceof Array true
function(){} instanceof Function true
3、constructor
- null 和 undefined 无constructor,无法判断
- constructor是原型prototype的一个属性,当函数被定义时候,js引擎会为函数添加原型prototype,并且这个prototype中constructor属性指向函数引用, 因此重写prototype会丢失原来的constructor
- 如果自定义对象,开发者重写prototype之后,原有的constructor会丢失,因此,为了规范开发,在重写对象原型时一般都需要重新给 constructor 赋值,以保证对象实例的类型不被篡改
"".constructor==String
new Number().constructor==Number
true.constructor==Boolean
new Function().constructor==Function
new Date().constructor==Date
new Error().constructor==Error
[].constructor==Array
document.constructor==HTMLDocument
window.constructor==Window
4、Object.prototype.toString.call()
- toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型
- 对于 Object 对象,直接调用 toString() 就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息
Object.prototype.toString.call('') ; [object String]
Object.prototype.toString.call(1) ; [object Number]
Object.prototype.toString.call(true) ; [object Boolean]
Object.prototype.toString.call(Symbol()); [object Symbol]
Object.prototype.toString.call(undefined) ; [object Undefined]
Object.prototype.toString.call(null) ; [object Null]
Object.prototype.toString.call(new Function()) ; [object Function]
Object.prototype.toString.call(new Date()) ; [object Date]
Object.prototype.toString.call([]) ; [object Array]
Object.prototype.toString.call(new RegExp()) ; [object RegExp]
Object.prototype.toString.call(new Error()) ; [object Error]
Object.prototype.toString.call(document) ; [object HTMLDocument]
Object.prototype.toString.call(window) ; [object global] window 是全局对象 global 的引用