Skip to content
robrobbins edited this page Sep 10, 2013 · 5 revisions

Using Object.create

When you wish to make a subclass of an existing sudo Class Object you must do two things:

  1. Create a "constructor" function for your new subclass

  2. Use the Object.create method to inherit the prototype of the Class Object you want

    // the 'constructor' var Foo = function(el, data) { // works because sudo.View used the 'sudo.inherit' method this.construct(el, data); }; // clone the View Class Object's prototype Foo.prototype = Object.create(sudo.View.prototype); // add your code Foo.prototype.bar = function(baz) {...};

How This Works

There are two noteworthy things in the above example. One, we can call to the "super constructor" of our Foo View subclass via the this.construct() method. Two, in order to inherit the methods on the sudo.View prototype we must "clone" it with the Object.create method.

A Constructor Caveat

If you were to subclass the Foo Class Object above the same way it suclassed sudo.View with a Bar class, then create a bar instance, that bar instance would not inherit the constructor Foo on its prototype chain. This is a point of great confusion, but it's easy to understand. The bar instance has a prototype that is made up of Bar < Foo < sudo.View (and on...), but nowhere was the Foo "constructor" function placed on that prototype chain.

Could you place the Foo constructor on its own prototype to remedy that issue? Yeah, if you like call stack exceeded errors because of infinite recursion.

The Inherit Method

Generally, we subclass sudo Class Objects in a "One level Deep" kind of fashion. If however you are wanting to make a subclass that is in turn going to be subclassed you should use the sudo.inherit method to place the initial "constructor" function on the prototype chain. From the sudo.Model:

sudo.Model = function(data) {
  sudo.Base.call(this);
  this.data = data || {};
  // only models are `observable`
  this.callbacks = [];
  this.changeRecords = [];
};
// Model inherits from sudo.Base
sudo.inherit(sudo.Base, sudo.Model);

Notice that the sudo.Model function calls to sudo.Base explicitly. This is because Class objects that use the sudo.inherit() pattern cannot use the construct() convenience method. Why? Because sudo.inherit above does 2 things:

  1. It clones the sudo.Base prototype as the prototype for sudo.model using Object.create() just like the typical inheritance pattern shown in the Foo example.
  2. It places Sudo.Model on its own prototype as the constructor. This allows sublasses of sudo.Model to use the this.construct() convenience method (properly calling the sudo.Model Function as expected) but prevents the sudo.Model "contructor" from using it.

...more soon

Clone this wiki locally