Read more

How to call overwritten methods of parent classes in Backbone.js

Arne Hartherz
February 12, 2014Software engineer at makandra GmbH

When you are working with Backbone models and inheritance, at some point you want to overwrite inherited methods but call the parent's implementation, too.
In JavaScript, there is no simple "super" method like in Ruby -- so here is how to do it with Backbone.

Example

BaseClass = Backbone.Model.extend({
  initialize: function(options) {
    console.log(options.baseInfo);
  }
});

MyClass = BaseClass.extend({
  initialize: function(options) {
    console.log(options.myInfo);
  }
});

new MyClass({ myInfo: 'Hello World.', baseInfo: 'Hello Universe!' });
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

When you do that, MyClass will only run its own initialize method, and you'd get this console output:

Hello World.

How to super

But we want initialize of BaseClass to run as well -- and if you want to call a method in JavaScript, you need to do exactly that.

Backbone offers a shortcut that is not too ugly, and looks like this:

MyClass = BaseClass.extend({
  initialize: function(options) {
    console.log(options.myInfo);
    this.constructor.__super__.initialize.apply(this, arguments);
  }
});

That will call the parent's initialize method with the arguments that your method received. The console output is now what we want:

Hello World.
Hello Universe!

If you want to have a different method signature, you may pass a different array than arguments, or just use call:

MyOtherClass = BaseClass.extend({
  initialize: function(foo, bar, baz) {
    // ...
    this.constructor.__super__.initialize.call(this, { baseInfo: bar });
  }
});

Old versions of Backbone.js

Apparently there was no this.constructor in older versions of Backbone.js, and you'd have to explicitly name your parent class (which is a bit less robust). The approach shown above has been used on Backbone 1.1 and probably works for you as well. If you run into trouble, you might want to check a StackOverflow about accessing the parent class Show archive.org snapshot .

Posted by Arne Hartherz to makandra dev (2014-02-12 10:56)