JavaScript七种内置类型:web
除对象以外,其余统称为基本类型数组
typeof运算符后面跟操做数,typeof operand 或者 typeof (operand),返回一个类型的字符串值。函数
typeof undefined === "undefined" // true typeof true === "boolean" // true typeof 1 === "number" // true typeof 'test' === "string" // true typeof {} === "object" // true typeof Symbol() === "symbol" // true
typeof null === "object" typeof function () {} === "function" typeof [1] === "object"
typeof 对null的处理有问题,正确的结果应该是"null",可是实际返回的是"object",这个bug由来已久,也许之后也不会修复。
typeof function() {}返回的是一个"function",彷佛function也是JavaScript的一个内置对象,实际上函数是一个可调用对象,它有一个内部属性[[Call]],该属性使其能够被调用。
typeof [1]返回"object",说明数组也是object类型,实际上它是object的一个子类型,和普通对象经过字符串键索引不一样,数组经过数字按顺进行索引。工具
typeof是检测基本数据类型的最佳工具,可是检测引用类型的值时做用不大,都会返回"object",这时候就须要instance操做符了。instance运算符用于测试构造函数的protytpe属性是否出如今对象的原型链中的任何位置。
用法:object instanceof constructor,object: 要检测的对象,constructor某个构造函数测试
function A() {} function B() {} function C() {} A.prototype = new C() const a = new A() console.log(a instanceof A) // a是A类的实例 true console.log(a instanceof C) // A继承C true console.log(a instanceof B) // a不是A类的实例 false console.log(a instanceof Object) // Object实全部引用类型的父类 true console.log(A.prototype instanceof Object) // true A.prototype = {} a1 = new A() console.log(a1 instanceof A) // true console.log(a instanceof A) // false const date = new Date() console.log(date instanceof Date) // true
function instance_of(L, R) {//L 表示左表达式,R 表示右表达式 var O = R.prototype;// 取 R 的显示原型 L = L.__proto__;// 取 L 的隐式原型 while (true) { if (L === null) return false; if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true return true; L = L.__proto__; } }
想要对instanceof运算符有更加深刻的了解车票spa
toString()方法返回一个表示该对象的字符串,每一个对象都有一个toString()方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认状况下,toString()方法被每一个Object对象继承。若是此方法在自定义对象中未被覆盖,toString()返回"[object type]",其中type是对象的类型
prototype
const toString = Object.prototype.toString console.log(toString.call(null)) // [object Null] console.log(toString.call(undefined)) // [object Undefined] console.log(toString.call(new String)) // [object String] console.log(toString.call(Function)) // [object Function] console.log(toString.call(new Date)) // [object Date] console.log(toString.call('new Date')) // [object String] console.log(toString.call(['a'])) // [object Array]
从示例能够看出,Object.prototype.toString.call()能够准确表示数值的类型code