/* // 面试题:重写 instanceof
// obj:要检测的实例对象「原始值类型检测结果都是false」
// Ctor:要检测的构造函数
// 原理:一级级的去查找obj的原型链,如果其中某一次查找的内容正好是Ctor.prototype,则结果是true;如果找到Object.prototype还没有出现Ctor.prototype,则结果是false...
var instance_of = function instance_of(obj, Ctor) {
// 校验Ctor的格式
if (typeof Ctor !== "function") throw new TypeError('Right-hand side of instanceof is not callable');
if (!Ctor.prototype) throw new TypeError('Function has non-object prototype undefined in instanceof check');
// 原始值类型直接返回false
if (obj === null || !/^(object|function)$/i.test(typeof obj)) return false;
// 兼容Symbol.hasInstance的浏览器,应该使用这个处理
if (typeof Symbol !== "undefined") return Ctor[Symbol.hasInstance](obj);
// 一级级的获取obj的原型链「Object.getPrototypeOf获取某个实例对象的原型」
var proto = Object.getPrototypeOf(obj);
while (proto) {
if (proto === Ctor.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
};
console.log(instance_of([10, 20], Array)); //true
console.log(instance_of([10, 20], Object)); //true
console.log(instance_of([10, 20], RegExp)); //false */
面试题:重写instructor
最新推荐文章于 2024-07-12 10:43:17 发布