-
Notifications
You must be signed in to change notification settings - Fork 1
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
如何实现 instanceof 方法? #12
Labels
Comments
function myInstanceof(left, right) {
// 这里先用 typeof 来判断基础数据类型,如果是,直接返回 false
if (typeof left !== 'object' || left === null) return false;
// getPrototypeOf 是 Object 对象自带的 API,能够拿到参数的原型对象
let proto = Object.getPrototypeOf(left);
// 循环往下寻找,直到找到相同的原型对象
while (true) {
if (proto === null) return false;
// 找到相同原型对象,返回true
if (proto === right.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
}
// 验证一下自己实现的 myInstanceof 是否 OK
console.log(myInstanceof(new Number(123), Number)); // true
console.log(myInstanceof(123, Number)); // false |
|
const leftValueType = typeof leftValue
if (leftValueType !== 'object' && leftValueType !== 'function') return false 增加了一个判断来确定 |
棒! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: