Search code examples
javascriptprototype

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 you can see, if the prototype of a constructor is not an object, it will fail and throw an error. Is there a way to make sure instanceof will not fail?

typeof new A().constructor.prototype === "object"

and

typeof Object.getPrototypeOf(new A()) === "object"

apparently do not work.


Solution

  • The error says A.prototype needs to be an object, so you should check for that:

    function isObject(x) {
        return x != null && (typeof x == "object" || typeof x == "function");
    }
    

    but isObject(A.prototype) is not all you can do to assert an instanceof call won't throw. Going by the spec, you 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) {
            // any of the property accesses threw
            return false;
        }
    }