function A(){}
A.prototype = "Foo bar";
new A() instanceof A;
// TypeError: Function has non-object prototype 'Foo bar' in instanceof check
如您所见,如果构造函数的原型(prototype)不是对象,它将失败并抛出错误。有没有办法确保 instanceof
不会失败?
typeof new A().constructor.prototype === "object"
和
typeof Object.getPrototypeOf(new A()) === "object"
显然不起作用。
最佳答案
该错误表明 A.prototype
需要是一个对象,因此您应该检查这一点:
function isObject(x) {
return x != null && (typeof x == "object" || typeof x == "function");
}
但是 isObject(A.prototype)
并不是断言 instanceof
调用不会抛出的全部内容。根据规范,您应该测试
function allowsInstanceCheck(C) {
try {
if (!isObject(C)) return false;
var m = C[Symbol.hasInstance];
if (m != null) return typeof m == "function";
if (typeof C != "function") return false;
return isObject(C.prototype);
} catch (e) {
// any of the property accesses threw
return false;
}
}
关于javascript - 检查 "instanceof"是否会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268665/