1

I'm working on a highly object oriented project in JavaScript. I have an array[] of objects of different classes and I'm iterating through it and I want to check the class of the object at array[i]. Is there any way for me to detect this? This might help you understand what I mean:

var pieces = [new Pawn(), new Rook(), new Knight()];
for(var i = 0; i < pieces.length; i++){
    if(pieces[i] == Rook){
        //Do something with the rook
    }
}

This is the general idea of what I need to do, but the if condition is the tricky bit. How can I detect the class of the element at pieces[i]? My fallback solution is to give every object a "type" field.

1 Answer 1

2

This can depend on how you have inheritance set up, but in general you check that with the instanceof operator:

if(pieces[i] instanceof Rook) // ...
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful with instanceof, all it does is check that Rook.prototype is on the private [[prototype]] chain of pieces[i]. That may be OK depending on how you have implemented your inheritance and what you actually need to know. The constructor property might be more suitable (it's a public property so can be set to a suitable value when setting up inheritance initially).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.