作者:奥兰度
let toString = Object.prototype.toString.bind()function myInstanceof (object, constructor) {let tag = toString(constructor)if (tag === '[object Boolean]' ||tag === '[object String]' ||tag === '[object Number]' ||tag === '[object Undefined]' ||tag === '[object Null]' ||tag === '[object Symbol]' ||tag === '[object BigInt]' ||) {throw new Error(`Uncaught TypeError: Right-hand side of 'instanceof' is not an object`)}if (tag === '[object Array]' || tag === '[object Object]') {throw new Error(`Uncaught TypeError: Right-hand side of 'instanceof' is not callable`)}let proto = Object.getPrototypeOf(object)let prototype = constructor.prototypewhile(proto) {if (proto === prototype) {return true}proto = Object.getPrototypeOf(proto)}return false}
作者:安静
function myInstanceof(instance: any, oringin: any): boolean {if(instance == null ) return false; // undefined nullconst type = typeof instance;if(type !== 'object' && type !== 'function') return false; // 值类型let tempInstance = instance; // 防止修改 instancewhile(tempInstance) {if(tempInstance.__proto__ === oringin.prototype) return true; // 匹配上了// 未匹配tempInstance = tempInstance.__proto__; // 顺着原型链,向上查找}return false;}console.log(myInstanceof({}, Object)); // trueconsole.log(myInstanceof([], Object)); // trueconsole.log(myInstanceof([], Array)); // trueconsole.log(myInstanceof({}, Array)); // falseconsole.log(myInstanceof('abc', String)); // falseconsole.log(myInstanceof(100, Number)); // falseconsole.log(myInstanceof(null, Object)); // falseconsole.log(myInstanceof(undefined, Object)); // falsefunction fn(){}console.log(myInstanceof(fn, Function), 'fn'); // trueconsole.log(myInstanceof(fn, Object), 'fn'); // trueclass Foo {};const f1 = new Foo();console.log(myInstanceof(f1, Foo)); // trueconsole.log(myInstanceof(f1, Object)); // trueconsole.log(myInstanceof(f1, Array)); // false
作者:寥寥
function myInstanceof(left, right) {//这里先用typeof来判断基础数据类型,如果是,直接返回falseif (typeof left !== 'object' || left === null) return false;// 获取对象的原型let proto = Object.getPrototypeOf(left)// 获取构造函数的prototype对象let prototype = right.prototype// 判断构造函数的prototype对象是否在对象的原型链上while (true) {if (!proto) return false;if (proto === prototype) return true;proto = Object.getPrototypeOf(proto);}}
作者:不更新
/**** 用于检测构造函数prototype的属性是否出现在某个实例对象的原型链上* @param construction 构造函数* @param newObj 实例对象*/const instanceofIfNeeded = (construction, newObj) => {let constructionProto = Object.getPrototypeOf(construction);let newObjProto = Object.getPrototypeOf(newObj);while (true) {if (newObjProto == null) {return false;}if (constructionProto === newObjProto) {return true;}newObjProto = Object.getPrototypeOf(newObjProto);}};
作者:Leo
function myInstanceof(left, right) {if(typeof right !== 'object') throw new Error('Right-hand side of 'instanceof' is not an object');let proto = left.__proto__;if (!proto) return false;return right.prototype === proto ? true : myInstanceof(proto, right);}
作者
作者
作者
作者
