Search code examples
javascriptbackbone.js

Determine if JavaScript class extends another class


So suppose I had a class in Backbone:

var MyModel = Backbone.Model.extend( {} ); 

Using the instanceof operator I could check whether an instantiated object extended an object:

var instModel = new MyModel();
instModel instanceof MyModel; // true
instModel instanceof Backbone.Model; // true

I'd like to able to check inheritance without instantiating the object. Is there a means in JavaScript or Backbone to determine whether the uninstantiated class extends the object? Since:

 MyModel instanceof Backbone.Model; // false
 MyModel instanceof Function; // true

Solution

  • You can use instanceof like this:

    MyModel.prototype instanceof Backbone.Model
    

    This works because while there no instantiated instance of MyModel, you don't really care about it, you care about its prototype chain anyway, so you can just check its prototype inheritance.

    Note, this will not work for the specific check of

    MyModel.prototype instanceof MyModel
    

    That might be fine depending on your use-case, but it you do want that to work, you have two options:

    MyModel === MyModel && MyModel.prototype instanceof MyModel
    
    // OR
    
    Object.create(MyModel.prototype) instanceof MyModel