Open Hongbusi opened 2 years ago
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
function _instanceof(leftValue, rightValue) { rightValue = rightValue.prototype leftValue = leftValue.__proto__ while (true) { if (leftValue === null) return false if (leftValue === rightValue) return true leftValue = leftValue.__proto__ } }
洪总这里有个小问题
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
增加了一个判断来确定 leftValue
值的类型。 @luckept
const leftValueType = typeof leftValue if (leftValueType !== 'object' && leftValueType !== 'function') return false
增加了一个判断来确定
leftValue
值的类型。 @luckept
棒!