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我以前怎麼沒想到這件事?謝謝。 –