javascript - Check if "instanceof" is going to fail -
function a(){} a.prototype = "foo bar"; new a() instanceof a; // typeerror: function has non-object prototype 'foo bar' in instanceof check
as can see, if prototype of constructor not object, fail , throw error. there way make sure instanceof
not fail?
typeof new a().constructor.prototype === "object"
and
typeof object.getprototypeof(new a()) === "object"
apparently not work.
the error says a.prototype
needs object, should check that:
function isobject(x) { return x != null && (typeof x == "object" || typeof x == "function"); }
but isobject(a.prototype)
not can assert instanceof
call won't throw. going spec, should test
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) { // of property accesses threw return false; } }
Comments
Post a Comment