四大数据类型检测底层机制
typeof
返回结果是一个字符串,字符串中包含了对应的数据类型"number/string/boolean/undefined/symbol/bigint/object/function" typeof null => “object” => 原理:按照计算机底层存储的二进制结果来检测,对象都是以 000… 开始的 => 无法细分普通对象还是数组等对象 instancof
用来检测当前实例是否属于这个类,不是来检测数据类型的 一般只应用于普通对象/数组对象/正则对象/日期对象的具体细分 let arr = [ ] ;
console. log ( arr instanceof Array ) ;
console. log ( arr instanceof Object ) ;
console. log ( arr instanceof RegExp ) ;
不能应用于原始值类型let n = 10 ;
let m = Number ( 10 ) ;
console. log ( n instanceof Number ) ;
console. log ( m instanceof Number ) ;
小问题function person ( ) { }
person. prototype = Array . prototype;
let p1 = new person ;
console. log ( p1 instanceof Array ) ;
原理let arr = [ ] ;
console. log ( arr instanceof Array ) ;
console. log ( Array[ Symbol. hasInstance] ( arr) ) ;
let obj = { } ;
console. log ( arr instanceof obj ) ;
constructor
一样不是用来数据类型检测的,原本就是获取实例的构造函数 => 比 instanceof 好用 let arr = [ ] ;
console. log ( arr. constructor === Array) ;
console. log ( arr. constructor === Object) ;
console. log ( arr. constructor === RegExp) ;
重定向会和 instanceof 一样有问题 let arr = [ ] ;
function person ( ) { }
person. prototype = Array . prototype;
let p1 = new person ;
console. log ( p1. constructor === Array)
基本类型值可以使用 let n = 10 ;
let m = Number ( 10 ) ;
console. log ( n. constructor === Number) ;
console. log ( m. constructor === Number) ;
Object.prototype.toString.call([value])
专门用来检测数据类型的(强大且暴力!基本零瑕疵) 返回结果[object, 对象[Symbol.toStringTag]||对象.构造函数(不受自己更改影响)||Object] 非内置类 class person {
get [ Symbol. toStringTag] ( ) {
return 'person'
}
}
let p1 = new person ;
console. log ( Object . prototype. toString . call ( p1) ) ;
重写 instanceof
function instance_of ( test, origin ) {
if ( test == null || ! / ^(object|function)$ / i . test ( typeof test) ) return false ;
if ( typeof origin !== 'function' ) {
throw new TypeError ( "Right-hand side of 'instance_of' is not an object" ) ;
}
let proto = test. __proto__,
prototype = origin. prototype
while ( true ) {
if ( proto === prototype) return true ;
proto = proto. __proto__;
if ( proto == null ) return false ;
}
}