typeof 与 instanceof 的区别,实现一个全局通用的数据类型判断方法
typeof 和 instanceof 是 JavaScript 中两个常用的数据类型判断方法,它们之间有以下区别:
typeof
- typeof 是一个一元操作符,可以返回一个字符串,表示操作数的数据类型。
- typeof 可以判断基本数据类型(number、string、boolean、undefined、symbol、bigint)以及函数。
- 对于 null、数组和对象,typeof 都会返回"object"。
typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'
PS:如果你需要在 if 语句中判断是否为 null,直接通过 === null 来判断就好。
如果想要判断一个变量是否存在,可以使用 typeof a != ‘undefined’ (不能使用 if (a), 若 a 未声明,则报错)。
instanceof
-
instanceof 是一个二元操作符,可以判断一个对象是否是某个构造函数的实例。
-
instanceof 会沿着对象的原型链进行检查,直到找到与构造函数的 prototype 属性匹配的对象。
// instanceof 的实现原理,仅供参考 function myInstanceof(left, right) { // 这里先用typeof来判断基础数据类型,如果是,直接返回false if(typeof left !== 'object' || left === null) return false; // getProtypeOf是Object对象自带的API,能够拿到参数的原型对象 let proto = Object.getPrototypeOf(left); while(true) { if(proto === null) return false; if(proto === right.prototype) return true;//找到相同原型对象,返回true proto = Object.getPrototypeof(proto); } }
-
它可以准确地判断引用数据类型(object、array、function 等)。
typeof 与 instanceof 的区别
typeof与instanceof都是判断数据类型的方法,区别如下:
-
typeof会返回一个变量的基本类型,instanceof返回的是一个布尔值。
-
instanceof 可以准确地判断复杂引用数据类型,但是不能正确判断基础数据类型。
-
而 typeof 也存在弊端,它虽然可以判断基础数据类型(null 除外),但是引用数据类型中,除了 function 类型以外,其他的也无法判断。
可以看到,上述两种方法都有弊端,并不能满足所有场景的需求
如果需要通用检测数据类型,可以采用 Object.prototype.toString,调用该方法,统一返回格式为 “[object Xxx]” 的字符串。
如下:
Object.prototype.toString({}) // "[object Object]"
Object.prototype.toString.call({}) // 同上结果,加上call也ok
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g) //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call(document) //"[object HTMLDocument]"
Object.prototype.toString.call(window) //"[object Window]"
全局通用的数据类型判断方法
为了实现一个全局通用的数据类型判断方法,可以使用 Object.prototype.toString() 方法,它能够准确地返回对象的内部 [[Class]] 属性。
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}
console.log(getType(123)); // "number"
console.log(getType("hello")); // "string"
console.log(getType(true)); // "boolean"
console.log(getType(null)); // "null"
console.log(getType(undefined)); // "undefined"
console.log(getType([])); // "array"
console.log(getType({})); // "object"
console.log(getType(function() {})); // "function"
console.log(getType(new Date())); // "date"
console.log(getType(/pattern/)); // "regexp"
这种方式比单独使用 typeof 和 instanceof 更加通用和可靠。