1

Let's say I have a variable that could represent a number of different models (Objects). I want to respond to each differently, ideally through a switch statement. Is it possible to get the instanceof result as a value?

For example, something like this:

function determineModel(model) {
    switch (model instanceof) {  // this does not work
        case 'Foo':
            // do something
            break;
        case 'Bar':
            // do something else
            break;
        default:
    }
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
ebakunin
  • 3,621
  • 7
  • 30
  • 49

3 Answers3

1

You can use model.constructor.name:

switch (model.constructor.name) {
    case "Foo":
        //Do something
    case "Bar":
        //Do something
    default:
        //Default something
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Something like this should work:

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());
Jonathan Gray
  • 2,509
  • 15
  • 20
0

You could go for model.constructor.name and even without the switch statement:

function determineModel(model) {
    return {
      Foo: someFnFoo,
      Bar: someFnBar,
    }[model.constructor.name](); // Execute someFn* given the Object's constr. name
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313