检查给定的值是否是给定类或超类的实例,可以传递给函数的数据类型没有限制。例如,值或类或undefined
方案一、通过原型链检查
var checkIfInstanceOf = function(obj, classFunction) {
if(obj === null || obj === undefined || classFunction === null || classFunction === undefined) {
return false;
}
while(obj.__proto__ !== null) {
if (obj.__proto__ === classFunction.prototype) {
return true;
} else {
obj = obj.__proto__;
}
}
return false;
};
方案二、instanceof 检查
var checkIfInstanceOf = function(obj, classFunction) {
if (obj === null || obj === undefined || !(classFunction instanceof Function)) {
return false;
}
return Object(obj) instanceof classFunction;
};