JavaScript’s “super” Pattern


Most other languages make it easy to call the “super” function when you override method – to call the original method that you are overriding. JavaScript, unfortunately, doesn’t have a “super” or “base” or anything like that at this point.There are ways around this, though, all of which involve getting a reference to the prototype of your type, and calling the method directly.

The Super Pattern

The “super-method” pattern is where you call the parent type’s method from your own method. For example, overriding the toJSON method of a model:

var MyModel = Backbone.Model.extend({

  // a super-method
  toJSON: function(){

    // call the "super" method - 
    // the original, being overriden
    var json = Backbone.Model.prototype.toJSON.call(this);

    // manipulate the json here
    return json;
  }
});

This will call the toJSON method of the type from which the new type was extended. It’s a little more code than other languages, but it still gets the job done.

There are a lot of different ways to get to and call the methods of a prototype object. If you’d like to learn more, check out my triple pack of screencasts covering Scope, Context and Objects & Prototypes.

Also be sure to check out my Building Backbone Plugins e-book, from which this post was taken.

Let Me Teach You Arduino, With JavaScript!