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:
var myclass = function(){...}
function myclass(){...}
Those two methods are very different:
- creates an anonymous function and assigns it to the variable myclass
- 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 | var Person = Class.extend({ |
As you can see, both class names are Class
:
1 | p.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.