第76天 说说instanceof和typeof的实现原理并自己模拟实现一个instanceof
Activity
xxf1996 commentedon Jul 1, 2019
instanceof
:利用原型链判断“父级”的原型(prototype
)对象是否在“实例”的原型链上;typeof
:直接根据变量值得内存标识符进行判断;yxkhaha commentedon Jul 1, 2019
typeof 一般用来判断 number、string、boolean、undefined、object、function、symbol这七中类型。
js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息:
000:对象
010:浮点数
100:字符串
110:布尔
1:整数
instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置
ooo1l commentedon Dec 6, 2019
@t532 请问能举个命中这个 if 的例子么
ZindexYG commentedon Dec 20, 2019
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
smile-2008 commentedon Jan 26, 2021
xiaoqiangz commentedon Jun 21, 2022
typeof: 一般用来判断基本类型数据类型
instanceof: 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
function new_instanceof(oldP, newP) {
let protype = newP.prototype
let left = oldP.proto
while(left) {
if (left === protype) {
return true
} else {
left = left.proto
}
}
return false
}
mohaixiao commentedon Jun 21, 2022
instanceof原理
1.instanceof作用
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。是就返回true,不是就返回false。
2.实现原理
当使用instanceof时,如果class上有静态方法 Symbol.hasInstance,那就直接调用这个方法,如果没有就使用 obj instanceOf Class 检查 Class.prototype 是否等于 obj 的原型链中的原型之一。
手写instanceof
typeof原理
js 在底层存储变量的时候,会在变量的机器码的低位1-3位存储其类型信息: 对象:000 浮点数:010 字符串:100 布尔:110 ”。typeof直接根据变量值得内存标识符进行判断并返回的是对应字符串形式的值。
ytdxxt10 commentedon Nov 3, 2022
instanceof: 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
可以用链表思想实现
panpanxuebing commentedon Dec 16, 2024