直接上代码,解析见注释
// 使用示例
function Person( ) {
console.log( 'person实例化' )
}
let person = new Person( )
console.log( person instanceof Object)
console.log( person instanceof Person)
console.log( 1 instanceof Number)
let a = 1
let b = '1'
let c = false
let d = null
let e = undefined
let f = Symbol( 'a' )
console.log( Object.prototype.toString.call( a))
console.log( Object.prototype.toString.call( b))
console.log( Object.prototype.toString.call( c))
console.log( Object.prototype.toString.call( d))
console.log( Object.prototype.toString.call( e))
console.log( Object.prototype.toString.call( f))
// 自定义instanceof用法
// person._instanceof( Person)
// 但是我们不确定person的类型,可以是基本类型,对象,数组类型等等
// person instanceof Array
// 所以我们的使用方法是_instanceof( left,right)
// 规则,传入一个类型,返回true/false
// 判断这个实例是否是属于Object或者是否属于继承来的属性或者是构造函数
// 但是我们总的来说,object是所有类型的尽头
// 所以我们需要遍历原型链,找到类型并且返回
// 优化
// 对基本类型的判断
// let _proto = left.__proto__
// let _prototype = right.prototype
// if( _proto == = _prototype) {
// return true
// }
// 尽头Object.prototype.__proto__ = null
// 找到了尽头也没找到
// if( _proto == = null) {
// return false
// }
// 继续往上找
// left = left.__proto__
// while( 1) {
// if( _proto == = _prototype) {
// return true
// }
// 尽头Object.prototype.__proto__ = null
// 找到了尽头也没找到
// if( _proto == = null) {
// return false
// }
// 继续往上找
// left = left.__proto__
// }
//
// 完整实现
function _instanceof( left,right) {
// 如果是基本类型,我们就返回false
// 当然我们还需要关注的是基本包装类型 new String( )
const baseType = [ '[object String]' ,'[object Boolean]' ,'[object Number]' ,'[object Null]' ,'[object Undefined]' ,'[object Symbol]' ]
if( baseType.includes( Object.prototype.toString.call( left)) ) {
return false
}
let _proto = left.__proto__
let _prototype = right.prototype
while( 1) {
if( _proto == = _prototype) {
return true
}
// 尽头Object.prototype.__proto__ = null
// 找到了尽头也没找到
if( _proto == = null) {
return false
}
// 继续往上找
_proto = _proto.__proto__
}
}
console.log( _instanceof( 1,Number))