javascript - 检查 "instanceof"是否会失败

标签 javascript prototype

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/

相关文章:

javascript - 重定义构造函数原型(prototype)后,对象构造函数指向原始构造函数而不是prototype.constructor

javascript - 改进javascript原型(prototype)继承

javascript - 使用 constructor.prototype 遍历原型(prototype)链

javascript - 在 Node.js 中,文件读取发生在文件写入之前

javascript - D3 对数刻度标签作为 10 的幂

javascript - 如何注销使用 OAuth2 登录 Google 的应用程序?

macros - Nunjucks:在宏中将对象作为参数传递

javascript - 奇怪的 javascript 行为 - 错误,除非以正确的顺序定义 'classes'

javascript - 如何在 jQuery 中欺骗点击

javascript - Vue 多选限制选项数