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(){

<span class="c1">// call the "super" method - </span>
<span class="c1">// the original, being overriden</span>
<span class="kd">var</span> <span class="nx">json</span> <span class="o">=</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Model</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">toJSON</span><span class="p">.</span><span class="nx">call</span><span class="p">(<span class="nx">this</span>);
// 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!
A Demo Of BoEBot, Johnny-Five And Bluetooth →