How to check whether a class derives from another class?

Hey :slight_smile:

I’m trying to detect whether a class which is unknown at runtime derives from a certain base class. The obvious way didn’t work:

if (SomeClass.prototype === BaseClass) {
    // do stuff
} 

How would I do this in Ember?

Just to be sure we’re talking about the same thing, inheritance does not exist in javascript. Be it ember or not. So there is no such a thing as a base class (or as a class actually).

Rather there are prototype chains, which get linked when you create a new object. You may check whether an object’s prototype chain includes another object using javascript instanceof operator.

var A = Ember.Object.extend();
var B = A.extend();
var a = A.create();
var b = B.create();

a instanceof A;            // true
b instanceof A;            // true
B instanceof A;            // false
B.prototype instanceof A;  // true

That is, B itself is not an instance of A, but when you use B to create an object, its prototype will include the link to A. The details of this depend on the object implementation you use. That of Ember keeps a separate object for “classes” and “instances”. create() and extend() actually share the same purpose of creating a new JS object, they only differ in the way they set it up.

It’s fun by the way, create() basically does that: return new this();

Oh yeah, of course I have to use instanceof on the prototype! Got that confused. Thanks a lot!