user3818284
user3818284

Reputation:

How can I check to see if an object is an instance of a certain set of prototypes in JavaScript?

I know I can check to see if an object contains any instances of a prototype like this:

for (var key in obj) {

    if ((obj[key] instanceof head) || (obj[key] instanceof body)) {

        console.log("Key Accepted: " + obj[key]);

    }

}

And I know I can check to see if an object is a member of a list of objects:

var fruitBasket = ["Banana", "Orange", "Apple", "Mango"];
if (fruitBasket.indexOf("Apple") !== -1) {

    console.log("There's an apple in this fruit basket!");

}

But how can I check to see if an object is an instance of a certain set of prototypes?

Upvotes: 1

Views: 40

Answers (1)

dee-see
dee-see

Reputation: 24078

If your browser supports it (IE9+), you can use some on an array of classes/functions.

var obj = ...,
    result = [Array, Number, Foo].some(function(clas) { return obj instanceof clas; });

result will be true if obj is an instance of Array, Number or Foo.

Without the some method you can simply iterate over the array with a for.

Upvotes: 2

Related Questions