内置类型
javaScript有七种类型:
- 空值(null)
- 未定义(undefined)
- 布尔值)(boolean)
- 数字(number)
- 字符串(string)
- 对象(object)
- 符号(symbol,ES6新增)
除对象之外,其他的统称为"基本类型",注意:array和function都是object的子类型
类型的判断方法
typeof
typeof undefined === 'undefined' // true
typeof boolean === true // true
typeof 123 === 'number' // true
typeof '456' === 'string' // true
typeof null === 'object' // true
typeof function a(){} === 'function' // true
typeof {age:18} === 'object' // true
// ES6新加入的类型
typeof Symbol() === 'symbol' // true
instanceof
instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型
{} instanceof Object;// true
constructor
当一个函数 F被定义时,JS引擎会为F添加 prototype 原型,然后再在 prototype上添加一个 constructor 属性,并让其指向 F 的引用。如下所示:
细节问题
- null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。
- 函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object
toString
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。
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(newFunction()) ;// [object Function]
Object.prototype.toString.call(newDate()) ;// [object Date]
Object.prototype.toString.call([]) ;// [object Array]
Object.prototype.toString.call(newRegExp()) ;// [object RegExp]
Object.prototype.toString.call(newError()) ;// [object Error]
Object.prototype.toString.call(document) ;// [object HTMLDocument]
Object.prototype.toString.call(window) ;//[object global] window 是全局对象 global 的引用
变量没有类型,但它们持有的值有类型。类型定义了值的行为特征