typeof
typeof 只能判断出基本数据类型,会将数组、对象、null 都会被判断为 object。具体的typeof使用可以参考我另一篇的博客:整理typeof返回值_程序猿小野的博客-CSDN博客
instanceof
instanceof 可以正确判断对象的类型,其内部运行机制是判断在其 原型链中能否找到该类型的原型。
console.log(undefined instanceof undefined); // TypeError: Right-hand side of 'instanceof' is not an object
console.log(null instanceof null) // TypeError: Right-hand side of 'instanceof' is not an object
不能判断unll和undefined,直接报错
console.log(2 instanceof Number) // flase
console.log('123abc' instanceof String) // flase
console.log(true instanceof Boolean) // flase
console.log(new String() instanceof String) // true
console.log(new String('String created with constructor') instanceof String) // true
console.log(new Number() instanceof Number) // true
console.log(new Date() instanceof Object) // true
console.log([] instanceof Array) // true
console.log(function () {} instanceof Function) // true
console.log({} instanceof Object) // true
可以看到,instanceof 只能正确判断引用数据类型,而不能判断基本数据类型。instanceof 运算符可以用来测试一个对象在其原型链 中是否存在一个构造函数的 prototype 属性。
function C() {}
var c = new C()
console.log(c instanceof C) // true,因为 Object.getPrototypeOf(c) === C.prototype
console.log(c.__proto__ === C.prototype); // true
C.prototype = {}
console.log(c instanceof C) // false,C.prototype 指向了一个空对象,这个空对象不在 c 的原型链上.
console.log(c.__proto__ === C.prototype); // false
总结typeof 和 instanceof 的区分
1. typoof 和 instanceof 都无法判断null,typoof返回Object,instanceof报错
2. typeof 可以判断undefined,而 instanceof 判断会报错
3. typeof 无法判断Array和Object,instanceof 可以
4. type 判断undefined 和null的区别(两个变量类型之间)
typeof undefined // "undefined"
typeof null // "object"
undefined == null // true
undefined === null // false
undefined != null // false
undefined !== null // true
Object.prototype.toString:
console.log(Object.prototype.toString.call(1)) // "[object Number]"
console.log(Object.prototype.toString.call('hi')) // "[object String]"
console.log(Object.prototype.toString.call({ a: 'hi' })) // "[object Object]"
console.log(Object.prototype.toString.call([1, 'a'])) // "[object Array]"
console.log(Object.prototype.toString.call(true)) // "[object Boolean]"
console.log(Object.prototype.toString.call(() => {})) // "[object Function]"
console.log(Object.prototype.toString.call(null)) // "[object Null]"
console.log(Object.prototype.toString.call(undefined)) // "[object Undefined]"
console.log(Object.prototype.toString.call(Symbol(1))) // "[object Symbol]"
console.log(Object.prototype.toString.call(BigInt(1))) // "[object BigInt]"
如果帮助到您了,可以留下一个赞👍告诉我