Javascript 是否可以将instanceof运算符结果作为值获取?

Javascript 是否可以将instanceof运算符结果作为值获取?,javascript,function,object,ecmascript-6,Javascript,Function,Object,Ecmascript 6,假设我有一个变量,可以表示许多不同的模型(对象)。我希望以不同的方式回应每一个问题,最好是通过switch语句。是否可以将instanceof结果作为值获取 例如,类似这样的内容: function determineModel(model) { switch (model instanceof) { // this does not work case 'Foo': // do something break;

假设我有一个变量,可以表示许多不同的模型(对象)。我希望以不同的方式回应每一个问题,最好是通过
switch
语句。是否可以将
instanceof
结果作为值获取

例如,类似这样的内容:

function determineModel(model) {
    switch (model instanceof) {  // this does not work
        case 'Foo':
            // do something
            break;
        case 'Bar':
            // do something else
            break;
        default:
    }
}

您可以使用
model.constructor.name

switch (model.constructor.name) {
    case "Foo":
        //Do something
    case "Bar":
        //Do something
    default:
        //Default something
}

您可以选择
model.constructor.name
,甚至不使用
开关
语句:

函数确定模型(模型){
返回{
Foo:SomefFoo,
酒吧:一些酒吧,
}[model.constructor.name]();//给定对象的constr.name执行someFn*
}

类似的方法应该会奏效:

function determineModel(model) {
    switch(model.constructor) {
        case SomeObject:
            console.log('Constructor is SomeObject');
            break;
        case OtherObject:
            console.log('Constructor is OtherObject');
            break;
        default:
            console.log('Constructor is ' + model.constructor.name);
        }
    }

determineModel(new OtherObject());

那么
model.constructor
呢?这将为您提供对构造函数的引用这可能会为您提供所需的: