第76天 说说instanceof和typeof的实现原理并自己模拟实现一个instanceof
instanceof
boolean
[Symbol.hasInstance]
static method 来判断一个 object 是否是一个 class 的 instanceinterface IConstructor<T> {
new(...args: any[]): T
}
function isObject(o: any) {
return (typeof o === 'object' || typeof o === 'function') && o !== null
}
function instanceOf<T>(obj: any, cls: IConstructor<T>): obj is T {
if (isObject(cls)) {
if (typeof cls[Symbol.hasInstance] === 'function')
return cls[Symbol.hasInstance](obj)
else if (typeof cls === 'function') {
if (isObject(cls.prototype))
return cls.prototype.isPrototypeOf(obj)
else return false
} else throw new TypeError('cls is not callable')
} else throw new TypeError('cls is not an object')
}
typeof
'string', 'number', 'undefined', 'boolean', 'object', 'function', 'symbol'
instanceof
:利用原型链判断“父级”的原型(prototype
)对象是否在“实例”的原型链上;typeof
:直接根据变量值得内存标识符进行判断;1:整数
instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置
function new_instance_of(leftVaule, rightVaule) {
let rightProto = rightVaule.prototype; // 取右表达式的 prototype 值
leftVaule = leftVaule.__proto__; // 取左表达式的__proto__值
while (true) {
if (leftVaule === null) {
return false;
}
if (leftVaule === rightProto) {
return true;
}
leftVaule = leftVaule.__proto__
}
}
else if (typeof cls === 'function') { if (isObject(cls.prototype)) return cls.prototype.isPrototypeOf(obj) else return false }
@t532 请问能举个命中这个 if 的例子么
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
function instance_of(left, right) {
const RP = right.prototype; // 构造函数的原型
while(true) {
if (left === null) {
return false;
}
if (left === RP) { // 一定要严格比较
return true;
}
left = left.__proto__; // 沿着原型链重新赋值
}
}
Most helpful comment
instanceof
boolean
[Symbol.hasInstance]
static method 来判断一个 object 是否是一个 class 的 instancetypeof
'string', 'number', 'undefined', 'boolean', 'object', 'function', 'symbol'