系列文章目录
前言
提示:JS中的typeof和instanceof都是用来判断数据类型的,但是你对他们了解多少呢
一、typeof 与 instanceof ?
typeof:用来判断基本数据类型 ,可以正确判断的数据类型如下:
Number、String、Boolean、undefined、Function
instanceof:用来判断引用类型,可以正确判断的数据类型如下:
Object、Array、Function、Date、RegExp
二、为什么typeof判断null为object?
这是一个历史遗留问题,JS设计之初使用的是32位二进制,为了考虑性能问题,采用的是低位存储变量,规定"000"开头的为引用列类型,而null表示为全0,所以才会被错误的认为是对象
三、写myTypeof函数,使之可以判断所有类型
代码如下:
function myTypeof(variable){
// 如果需要判断的是null,直接返回 'object'
if (variable === null) return 'object'
// 如果需要判断的是基本数据类型,直接使用typeof判断 ; 反之使用 Object.prototype.toString.call()
else return typeof variable !== 'object' ? typeof variable
: Object.prototype.toString.call(variable).split(' ')[1].replace(']','')
}
console.log(myTypeof(1))
console.log(myTypeof('string'))
console.log(myTypeof(true))
console.log(myTypeof(function() {}))
console.log(myTypeof([]))
console.log(myTypeof({}))
结果截图:
提示:myTypeof函数都写了,没有Instanceof也不能少吧!!!
实例对象获取原型对象的方法有哪些? __proto__ 或者 getPrototypeOf
四、实现myInstanceof函数
代码如下:
function myInstanceof(left,right){
if (typeof left !== 'object' || left === null) {
if (typeof left !== 'function') return false
}
let proto = left.__proto__
while(true){
if (proto === right.prototype) return true
if (proto === null) return false
proto = proto.__proto__
}
}
console.log(myInstanceof(1,Number))
console.log(myInstanceof(null,Object))
console.log(myInstanceof(function (){},Function))
console.log(myInstanceof([],Array))
console.log(myInstanceof({},Object))
结果截图:
总结
望大家在前端之路共勉!!!