-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第76天 说说instanceof和typeof的实现原理并自己模拟实现一个instanceof #528
Comments
|
|
|
@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__; // 沿着原型链重新赋值
}
} |
|
typeof: 一般用来判断基本类型数据类型 |
instanceof原理 function instanceOf(object, constructor) {
let curProto = Object.getPrototypeOf(object);
// 每一层原型区检查,若相等就直接返回 true,退出
while(curProto) {
if(curProto === constructor.prototype) return true;
curProto = Object.getPrototypeOf(curProto);
}
// 没有退出,坚持到这的就是 false 了
return false;
} typeof原理 |
instanceof: 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
|
function myIntanceof (obj, fn) {
if (obj === null) return false
let proto = Object.getPrototypeOf(obj)
if (proto === fn.prototype) {
return true
}
return myIntanceof(proto, fn)
} |
第76天 说说instanceof和typeof的实现原理并自己模拟实现一个instanceof
The text was updated successfully, but these errors were encountered: