Javascript inheritance

I was reading through John Resig’s code recently and stumbled upon this comment:

“@Justin: I don’t think there’s a reasonable way to actually assign a name to the classes, which is unfortunate.”

The problem at stake: There are two ways to define a class in Javascript:

  1. var myclass = function(){...}
  2. function myclass(){...}

Those two methods are very different:

  1. creates an anonymous function and assigns it to the variable myclass
  2. declares the function named myclass

By definition, “you cannot change the name of a function, this property is read-only.”. Once one has started using an anonymous function to create a class, the class name can never be changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});

var Ninja = Person.extend({
init: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
}
});

var p = new Person(true);
var n = new Ninja();

As you can see, both class names are Class:

1
2
p.constructor.name; // 'Class'
n.constructor.name; // 'Class'

This can become ennoying when debugging large projects that heavily use anonymous functions.

By playing with the language’s inheritance concepts, and dynamic function naming, I built a tiny library that allowed the following:

  • Inheritance support (subclass methods can override / refer to their base methods)
  • Proper names for classes
  • Basic event management

The code is released under the MIT licence. It’ll be useful for building games or other object-oriented programs.

dark
sans