The confusion arising from this chapter of Crockford's book arises, as Crockford describes, โhisโ preferred pattern for implementing inheritance in JavaScript, which relies on his extension of the Function object with Function.prototype.method (chapter 1.3), which he uses to add methods to the Function object.
The problem discussed in the coolcat example is the need to access the parent type method. In "classic" OO languages, such as Java, this is natural because classes exist by themselves. In JavaScript, inheritance is prototyped, you create an object of type mammal , and then modify the object to create type cat or coolcat .
Depending on your design, you can add properties and functions or redefine the inherited function. The problem arises when you redefine an โinheritedโ function, in JavaScript you basically replace the old function with the new function, thereby losing the older function.
Crockford must now do two things:
- get the parent (cat's)
get_name ; and - save it in a way that can be used from an overridden method.
In this code:
var coolcat = function(spec) { var that = cat(spec), super_get_name = that.superior('get_name'); that.get_name = function(n) { return 'like ' + super_get_name() + ' baby'; }; return that; };
He does 1. by calling the superior method to get the function that gets the cat function get_name ; and he does 2. by storing it in the super_get_name variable in the coolcat (/ object) function, giving access to the cat get_name function before it is redefined (more correctly rewritten) using the coolcat get_name function.
In my opinion, the confusion arises from the fact that:
- The
superior method is called strange: the superior method is just a method for searching by name and can be better named, for example, as getFunctionByName (you can try replacing get_name with purr , coolcat get_name will now call purr, just remember to name it as super_get_name(10) , otherwise you will get an empty string). - Secondly, the code and the pattern trick the code into relying on some specific Crockford patterns, and you will probably be reproached if you try to dive into this chapter without following the entire book.
I think there is an easier way to achieve this, one that I think, because it is completely localized, easier to understand, etc., as in the code below:
var coolcat = function(spec) { var that = cat(spec); that.parent_get_name = that.get_name; that.get_name = function() { return 'like ' + this.parent_get_name() + ' baby'; }; return that; };
There are some other oddities, such as the argument n in the definition of the coolcat get_name function, which I can only assume when copying the purr function that the ghost writer would suggest!
Finally, I would suggest that before you read the book, you need to listen to his talk about "JavaScript good parts." The conversation is absolutely brilliant, much better than a book.