function instance_of(example,classFunc){
let classFuncPrototype = classFunc.prototype;
proto = Object.getPrototypeOf(example);
// example.__proto__
while(true){
if(proto === null){
// Object.prototype.__proto__ =>null
return false
}
if(proto === classFuncPrototype){
// 查找过程中发现有,则证明是实例是这个类的实例
return true
}
proto = Object.getPrototypeOf(proto)
}
}
// 实例.__proto__===类.prototype
let arr = []
console.log(instance_of(arr,Array))
console.log(instance_of(arr,RegExp));
console.log(instance_of(arr,Object));
- constructor
+ 用起来看似比instanceof还好用一些 + construction 可以随便更改,所以也不准
Number.prototype.constructor = 'AA'
let n=1
console.log(n.constructor === Numeber)
- Object.prototype.toString.call([value])
let obj = {name:'haha'}
// obj.toString();=>'[object,Object]'
// -> toString方法执行,this是obj,所以检测是obj它的所属的类信息
// 推测:是不是只要把Object.prototype.toString执行,让他里面的this变为要检测的值,那就能返回当前值所属类的信息
封装的类型检测方法
(function(){
var class2type={}
var toString = class2type.toString;//Object.prototype.toString
// 设定数据类型
["Boolean",'Number','String','Function','Array','Date','RegExp','Function','Object','Error','Symbol'].forEach(name=>{
class2type[`[object ${name}]`] = name.toLowerCase()
})
function toType(obj){
if(obj===null){
return obj+''
}
return typeof obj === 'object'||typeof obj === 'function'?
class2type[toString.call[obj]] || 'object' :
typeof obj
}
window.toType = toType
})()
``
|