Javascript- 有没有办法通过对象名称作为字符串来测试对象的 instanceof

Javascript- Is there a way to test instanceof of object by the object name as a string

我有下面的 JavaScript 片段。简而言之,我要实现的目标是;一种检查传递给函数的参数是否是某个预定 类 实例的方法。我知道我可以使用

if(obj instanceof className){ /* do stuff * / } else{ /* other things */ }
语句,但它会是庞大的代码,特别是如果我有一堆 类 来测试。简而言之,我怎样才能用下面的代码实现我想要做的事情?谢谢大家

class A {
    constructor(name) {
        this._name = name;
    }
}
class B {
    constructor(name) {
        this._name = name;
    }
}
class C {
    constructor(name) {
        this._name = name;
    }
}
let allTemplates = ['A', 'B', 'C', 'Object']; //available classes

let a = new A('A class');
let b = new B('B class');
let c = new C('C class');

function seekTemplateOf(obj) {
    /**find if @arg obj is an instance of any
     ** of the classes above or just an object
     **@return string "class that obj is instance of"
     **/
    return allTemplates.find(function(template) {
        return obj instanceof window[template];
        /*Thought that ^^ could do the trick?*/
    });
}
console.log(seekTemplateOf(a));
/*"^^ Uncaught TypeError: Right-hand side of 'instanceof' is not an object"*/

将您的字符串更改为引用:

let allTemplates = [A, B, C, Object];

然后检查对象构造函数是否等于:

const obj = new A;
const objClass = allTemplates.find(c => obj.constructor === c);

或者(如果一些原型黑客忘记设置 constructor)你可能会得到确定的原型:

const obj = new A;
const objClass = allTemplates.find(c => Object.getPrototypeOf(obj) === c.prototype);

或者您可以简单地使用 instanceof 然后:

const obj = new A;
const objClass = allTemplates.find(c =>  obj instanceof c);

您可以使用一个对象作为模板并再次检查给定的对象。

class A { constructor(name) { this._name=name; } }
class B { constructor(name) { this._name=name; } }
class C { constructor(name) { this._name=name; } }

let allTemplates = { A, B, C, Object };

let a = new A('A class');
let b = new B('B class');
let c = new C('C class');

function seekTemplateOf(obj) {
    return Object.keys(allTemplates).find(template => obj instanceof allTemplates[template]);
}

console.log(seekTemplateOf(a));