You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/*
instanceof 实现思路
es6给所有的构造函数添加了[Symbol.hasInstance]它的返回值就是instanceof的返回值
而有一些低版本浏览器不兼容es6的语法无法识别Symbol,那么它就按照原型链进行查找
*/
var myInstance_of = function myInstance_of(obj, ctor) {
if (typeof ctor === null && !/^(object|function)$/.test(typeof ctor))
throw new TypeError(
"Right-hand side of 'instanceof' is not an object"
);
// 判断传入的是否是一个函数
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"
);
// 不支持基本数据类型的检测
if (typeof obj === null && !/^(object|function)$/.test(typeof obj))
return false;
// 判断浏览器是否能识别Symbol
if (typeof Symbol !== "undefined") {
// es6给所有的构造函数都加上了[Symbol.haInstance]
const hasInstance = ctor[Symbol.hasInstance];
if (typeof ctor === "function") {
return hasInstance.call(ctor, obj);
}
// 从原型链查找进行判断
var protot = Object.getPrototypeOf(obj);
while (protot) {
if (protot === ctor.prototype) return true;
protot = protot.getPrototypeOf(protot);
}
return false;
}
};
The text was updated successfully, but these errors were encountered:
The text was updated successfully, but these errors were encountered: