-
Notifications
You must be signed in to change notification settings - Fork 1
inheritance
When you wish to make a subclass of an existing sudo Class Object you must do two things:
-
Create a "constructor" function for your new subclass
-
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) {...};
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.
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.
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:
- It clones the
sudo.Base
prototype as the prototype forsudo.model
usingObject.create()
just like the typical inheritance pattern shown in the Foo example. - It places Sudo.Model on its own prototype as the
constructor
. This allows sublasses ofsudo.Model
to use thethis.construct()
convenience method (properly calling thesudo.Model
Function as expected) but prevents thesudo.Model
"contructor" from using it.
...more soon