function A(){}
A.prototype = "Foo bar";
new A() instanceof A;
// TypeError: Function has non-object prototype 'Foo bar' in instanceof check
正如您所看到的,如果构造函数的原型不是对象,它将失败并抛出错误。有没有办法确保instanceof
不会失败?检查“instanceof”是否会失败
typeof new A().constructor.prototype === "object"
和
typeof Object.getPrototypeOf(new A()) === "object"
显然不起作用。
也许把它包装在'try/catch'中? – Barmar
'typeof A.prototype ===“object”'? – Barmar
@Barmar我以前怎么没想到这件事?谢谢。 –