Wednesday, 9 September 2009

Simple, Efficient Supercalls in JavaScript

In this post, I'll be outlining a simple means of doing supercalls in JavaScript without causing unnecessary runtime overhead, running into maintenance issues, or falling afoul of the new "strict" mode of ECMAScript 5.

Update 2012/04/04: A few weeks back I had one of those "ah hah" moments that you sometimes have, which made me realize that while the below is indeed efficient and simple enough to use, there's another way that's just as efficient and lots simpler, both to use and in terms of how much support code is required. And so I created the Lineage toolkit, see this announcement post for more.

The Short Version


The mechanism in brief is:
  • Have a "make a class" function (most libraries do).
  • In that function, detect that a subclass is overriding a superclass function and, if so, put a reference to the superclass function on the subclass function instance as a property.
  • To call a superclass function from a subclass function, authors use Function#call or Function#apply on the $super property of the subclass function instance (being sure to get the function directly, not via this). This is simplest and fastest with named functions, but possible with anonymous ones too.
  • Allow for mixins, if you're into that sort of thing (and why not, they're cool).
That's it. Dead simple, and dramatically more efficient than the wrapping subclass functions in closures, doing function decompilation (which has never been standardized), etc. It leads to more maintainable (and readable) code than having subclasses refer to their parents by name, and even encourages the use of named functions, which is a good idea for lots of other reasons.

Okay, on to the details, including a full sample implementation, and discussion around the various choices and issues.

What Lead To This


Let me step back a moment and explain how this came about. I have a project requiring a fair bit of server-side JavaScript and also object hierarchy. Not wanting to use "raw" JavaScript hierarchy or roll my own, I naturally reached for my favorite JavaScript library, Prototype, since this is one of the many things it does. Now, Prototype is currently tied to web browsers (something the core team are fixing even as I write this), so I figured until Prototype 2 comes out, I'd just copy the relevant parts (the Class class) and then switch to using Prototype 2 later when it comes out.

So I started doing that, but then remembered that I'm not a big fan of how Prototype does supercalls — you know, when a subclass overrides a superclass method but then wants to call the superclass's version. My initial issue was mostly with the API it provides (the superclass's function is a special parameter to the subclass function, which seems odd to me), but as I was copying Class over and reading through the code, and realized that what Prototype does under the covers to make supercalls work (which includes function decompilation, wrapping in closures, and creating a new function on every call to a supercall-enabled method) is an awful lot of runtime overhead.

So I thought: "Surely I could just tweak this a bit to..." Yes, that's right, I fell right into the anti-pattern of reinventing the wheel. But I'm glad I did, because it taught me a lot I didn't know before, and lead me (with some help from my friends) to come up with this dead-simple mechanism for supercalls. (Caveat: I can't imagine this mechanism is unique, but it was new to me.)

Hierarchy In JavaScript


I won't go into a thorough discussion of hierarchy in JavaScirpt, but suffice to say that whether you use Prototype or something else, it probably provides something that lets you create "classes" by calling a special helper function, passing in an object that has properties referencing the instance methods you want in your class, and getting back a constructor you can call:
// Defining the class
var SpiffyClass = Helper.makeClass({
initialize: function() {
// ...initialize an instance...
},
nifty: function() {
// ...do something nifty...
}
});

// Creating an instance
var spiffy = new SpiffyClass();
This pattern — passing an object literal into a helper function — has been very successful in recent years, and for good reason: It's terse but expressive. (There's a problem with it we'll come back to later, but it gets the job done.)

Inside The Helper


Let's look into the helper to see what it's doing. Here's a first-cut on what Helper.makeClass might look like — the code comments basically tell the story (download it here if the below is awkward to read; I hate Blogger!):
// Take I, doesn't help with supercalls.
// Inspired by Prototype's Class class (http://prototypejs.org)
// Copyright (C) 2009-2010 by T.J. Crowder
// Licensed under the Creative Commons Attribution License 2.0 (UK)
// http://creativecommons.org/licenses/by/2.0/uk/
var Helper = (function(){

// This function is used to create the prototype object for our generated
// constructors if the class has a parent class. See makeConstructor for details.
function protoCtor() { }

// Build and return a constructor; we do this with a separate function
// to minimize what the new constructor (a closure) closes over.
function makeConstructor(base) {

// Here's our basic constructor function (each class gets its own, a
// new one of these is created every time makeConstructor is called).
function ctor() {
// Call the initialize method
this.initialize.apply(this, arguments);
}

// If there's a base class, hook it up. We go indirectly through `protoCtor`
// rather than simply doing "new base()" because calling `base` will call the base
// class's `initialize` function, which we don't want to execute. We just want the
// prototype.
if (base) {
protoCtor.prototype = base.prototype;
ctor.prototype = new protoCtor();
protoCtor.prototype = {}; // Don't leave a dangling reference
}

// Set the prototype's constructor property so `this.constructor` resolves
// correctly
ctor.prototype.constructor = ctor;

// Return the newly-constructed constructor
return ctor;
}

// This function is used when a class doesn't have its own initialize
// function; since it does nothing and can only appear on base classes,
// all instances can share it.
function defaultInitialize() {
}

// makeClass: Our public "make a class" function.
// Arguments:
// - base: An optional constructor for the base class.
// - ...: One or more specification objects containing properties to
// put on our class as members. If a property is defined by more
// than one specification object, the last in the list wins.
// Returns:
// A constructor function for instances of the class.
//
// Typical use will be just one specification object, but allow for more
// in case the author is drawing members from multiple locations.
function makeClass() {
var base, // Our base class (constructor function), if any
argsIndex, // Index of first unused argument in 'arguments'
ctor, // The constructor function we create and return
members, // Each members specification object
name; // Each name in 'members'

// We use this index to keep track of the arguments we've consumed
argsIndex = 0;

// Do we have a base?
if (typeof arguments[argsIndex] == 'function') {
// Yes
base = arguments[argsIndex++];
}

// Get our constructor; this will hook up the base class's prototype
// if there's a base class
ctor = makeConstructor(base);

// Assign the members from the specification object(s) to the prototype
// Again, typically there's only spec object, but allow for more
while (argsIndex < arguments.length) {
// Get this specification object
members = arguments[argsIndex++];

// Copy its members
for (name in members) {
ctor.prototype[name] = members[name];
}
}

// If there's no initialize function, provide one
if (!('initialize' in ctor.prototype)) {
// Note that this can only happen in base classes; in a derived
// class, the check above will find the base class's version if the
// subclass didn't define one.
ctor.prototype.initialize = defaultInitialize;
}

// Return the constructor
return ctor;
}

// Return our public members
return {makeClass: makeClass};
})();
So far, nothing new, this is just the kind of thing you'll find in most libraries.

Supercalls


The helper as written is already really useful:
var Parent = Helper.makeClass({
nifty: function() {
return "Nifty!";
}
});
var Child = Helper.makeClass(Parent, {
spiffy: function() {
return "Spiffy!";
}
});
var c = new Child();
alert(c.nifty()); // Alerts "Nifty!" using Parent#nifty
alert(c.spiffy()); // Alerts "Spiffy!" using Child#spiffy
But what if we want to override #nifty in Child to do some processing on Parent's return value? Well, we can do that by going direct to the parent and using Function#call (or Function#apply), but the syntax is quite awkward:
var Child = Helper.makeClass(Parent, {
nifty: function() {
var rv = Parent.prototype.nifty.call(this);
return rv.toUpperCase();
},
spiffy: function() {
return "Spiffy!";
}
});
var c = new Child();
alert(c.nifty()); // Alerts "NIFTY!"
That works, but there are a few good reasons not to do it:
  • It's long-winded, inviting irritating mistakes.
  • It's makes re-basing a class difficult (every method that does this has that superclass name in it).
  • It makes moving code between classes difficult (ditto).
In short, it's a maintenance problem. Manageable, but a problem. And this is why most libraries try to address it in various ways, often involving adding closures and decompilation and indirection and whatnot. On the "up" side, the above is quite direct and performs very quickly. But what if we could get that directness and speed without getting all of that other stuff, and with brevity and maintainability?

We can.

With a Little Help(er) From My Friends


Our makeClass function has all of the information it needs to help us out: It can easily tell when we're overriding a base class function, and it can give us a reference to that function without our having to know the base class name. How? By putting it on our function instance. Remember that functions are first-class objects, we can put properties on them.

This turns out to be really easy. In makeClass, when copying the members from the specification object(s) to the new constructor's prototype, if a member we're copying is a function and we have a base and the base value is also a function, we stick it on the override function as $super. E.g., we replace these lines from earlier:
for (name in members) {
ctor.prototype[name] = members[name];
}
...with:
for (name in members) {
value = members[name];
if (base && typeof value == 'function') {
baseValue = base.prototype[name];
if (typeof baseValue == 'function') {
value.$super = baseValue;
}
}
ctor.prototype[name] = value;
}
(Also add the 'value' and 'baseValue' declarations at the top.)

So now we can get at our superclass's function by looking at the $super property on our own function. But how do we get that? In our Child#nifty function earlier, say, how do we get to Parent#nifty? If your first thought (like mine) is this.nifty.$super, I'm afraid you're not thinking it through — that will work only for one level of hierarchy, it will fail if anything (say, GrandChild) derives from Child and has its own #nifty function, because with a GrandChild instance, this.nifty is always GrandChild#nifty. If Child#nifty called this.nifty.$super in that situation, it would be calling itself, not Parent#nifty, recursing until the engine gave up on it. So this is out.

And here we run into an issue. We want to get at our current function object, but so far we haven't been giving our functions names. They're just anonymous functions we've assigned to properties on objects. The properties have names, but the functions do not, and we've just concluded we can't use the property (because we can only get to it via this, and that means it'll always point to the bottommost — GrandChild — function). So now what?

Well, there is a way, but it's a bit ugly (on a couple of fronts): arguments.callee. The arguments object, I'm sure you know, is an array-like object defined within functions that contains the arguments passed into the function. That object also has a property on it called callee that is a reference to the actual function object. So we can get at our super function using arguments.callee.$super. And like all other functions, we can call it and pass in the value to use as this by using the Function#call function. So:
var Child = Helper.makeClass(Parent, {
nifty: function() {
var rv = arguments.callee.$super.call(this); // Blech
return rv.toUpperCase();
},
});
alert(c.nifty()); // Alerts "NIFTY!"
That works, and is more efficient than most other schemes, but it has some issues:
  • It's long-winded, inviting irritating mistakes (wait, where have I heard that before?)
  • The new ECMAScript standard, 5th edition, has a "strict" mode in which arguments.callee (amongst other things) is disallowed (many thanks to John-David Dalton and Juriy Zaytsev — kangax — for pointing this out to me)
  • It's slow (although faster than many other ways of doing this), most browsers don't set up arguments.callee unless you use it, and they're pretty slow at setting it up (thanks again, kangax, for that one)
Still, it is functional (outside of strict mode). But what if we could get there another way without those problems?

You guessed it, we can. And in fact, we get a lot of other benefits when we do.

Named Functions


The problem is anonymous functions, and it's not the only problem with them either. Anonymous functions are tools-hostile. Our browsers can't tell us the name of the function in which an error occurred if it's anonymous. Our debuggers can't show us meaningful call stacks with anonymous functions (we just see a lot of question marks, usually). Etc.

So if the problem is anonymous functions, well, let's just give our functions names! That way, we can use the name directly, since a function's name is defined throughout the scope in which the function is defined (including within the function itself); that's how we usually write recursive functions, after all.

So when defining classes, how can we give our functions names? One's first thought might be to simply do this:
var Child = Helper.makeClass(Parent, {
nifty: function nifty() { // <= PROBLEMATIC
// ...
}
});
In some ways, that should work, but it has ramifications. The name "nifty" gets defined in the enclosing scope, which in our case above is global — not a good idea! And it flat out doesn't work with Internet Explorer (or anywhere you're using JScript) or Safari. (For the full story, check out Juriy's excellent article on the subject, it's a good read.)

No, it would be better to contain the scope a bit (not to mention working around bugs), which is easy enough: Wrap it up in a function:
var Child = Helper.makeClass(Parent, (function(){
function nifty() {
// ...
}
function spiffy() {
// ...
}
return {
nifty: nifty,
spiffy: spiffy
};
})());
That probably wants breaking down a bit:
  • We define an anonymous function for scoping
  • Within that scoping function, we define our various methods for Child — as named functions
  • Our function names are in scope throughout the scoping function
  • Our scoping function returns an object with the properties mapped to our named functions (I added a "spiffy" to this example just to make clear how it works with multiple functions)
  • We execute the scoping function immediately and pass the result (the object) into makeClass
No scope bleed, no issues with IE or Safari, we're all set.

So okay, but so far I've been leaving out the good bit — the supercall in Child#nifty! Here we go:
var Child = Helper.makeClass(Parent, (function(){
function nifty() {
var rv = nifty.$super.call(this);
return rv.toUpperCase();
}
function spiffy() {
// ...
}
return {
nifty: nifty,
spiffy: spiffy
};
})());
var c = new Child();
alert(c.nifty()); // Alerts "NIFTY!"
Within #nifty, we refer to the function by name — no this, that's very important! — which always refers to the right one. We get its $super property, and use Function#call on it. (We could use Function#apply if we wanted.) We pass in this as the context parameter so that this is correct within the supercall.

Revisiting makeClass


I floated this supercalls idea on the Prototype Core development mailing list, and Allen Madsen pointed out that if we're going to be using functions to create enclosing scope when defining classes, makeClass should just support our passing those functions in directly rather than making us execute them first. It simplifies the syntax markedly:
var Child = Helper.makeClass(Parent, function(){
function nifty() {
var rv = nifty.$super.call(this);
return rv.toUpperCase();
}
return {nifty: nifty};
});
var c = new Child();
alert(c.nifty()); // Alerts "NIFTY!"
We just define the function rather than defining and calling it; makeClass will call it for us. So let's go support that in makeClass (we'll still support providing the specification object directly) by marking constructor functions (so we know whether we have a base class, since everything might be a function now — this was also Allen's idea) and then just invoking any functions we find to get their specification objects. (Code below under "Bringing It All Together".)

Mixins


A fairly common pattern these days it to have "mixins" that can be mixed into classes. A "mixin" is a collection of functions that coordinate to provide some functionality, intended to be added to a class rather than to be a class in its own right. One mixin might be used by several different classes. Mixins are sometimes seen as a replacement for derivation, but to me they're an adjunct — there are times you derive, and other times you mix in.

Mixins are the reason that Helper.makeClass allows multiple specification objects. Suppose we have a mixin that provides semantics around getting and setting a "cool" property:
var CoolMixin = (function(){
function setCool(cool) {
if (typeof cool != 'string') {
throw "Hey, man, that ain't cool.";
}
this.cool = cool;
}

function getCool() {
return this.cool;
}

return {getCool: getCool, setCool: setCool};
})();
Now we can mix that into any class:
var CoolChild = Helper.makeClass(Parent, CoolMixin, function() {
function spiffy() {
// ...
}
return {spiffy: spiffy};
});
var cc = new CoolChild();
alert(cc.nifty()); // Alerts "Nifty!" via Parent#nifty
cc.setCool(1); // throws the uncool exception
CoolChild inherits from Parent, but also gets the cool stuff from CoolMixin. By convention (and in order to ensure that a subclass's own members take precedence), mixins are always included after the parent and before the child's own members.

Mixins raise an issue for makeClass: Normally, it modifies function instances, setting a $super property on them if they override a base class function (it leaves them alone if they don't). But mixins are used in multiple classes, so we shouldn't touch them. While in practice it would be fairly harmless to set $super on the mixin function if the mixin function didn't call $super (which is definitely an edge case), it's still not right and in certain very edgy edge cases could cause class cross-talk, which is a Bad Thing(tm).

To handle this, we can provide a means of marking methods as being mixin methods and telling makeClass to leave them alone. (I actually mark the methods rather than doing it by context because some implementations — like Prototype — allow modifying hierarchies after initial derivation, in which case it's really important to know which functions are mixin functions and which aren't). It may seem to be pandering to an edge case, but there's effectively no runtime cost and the code is trivial, so let's do it — see Helper.makeMixin below.

Alternately, we can take a page from previous implementations and — in this one very specific case — wrap the mixin function so we can set the $super property on the wrapper. I haven't done that here, but it's a viable solution if you think mixins calling $super is a common enough use case for you.

Anonymouses Anonymous


Not everyone will want to use named functions; perhaps they have a large amount of legacy code using specification objects directly. Rather than leave them with the ugly syntax:
arguments.callee.$super.call(this, ...);
...let's give them a helper method to take on some of that complexity:
this.callSuper(arguments, ...);
But we don't want to do that all the time. Hey, that's the case for a mixin! See the CallSuperMixin below.

Bringing It All Together


Okay, taking all of the above, mixing in an IE workaround (thank you, Prototype!), and adding in Helper.makeMixin, we end up with this:
// Take IV: Explicitly handle mixins, provide a mixin for calling super when
// working with anonymous functions.
// Inspired by Prototype's Class class (http://prototypejs.org)
// Copyright (C) 2009-2010 by T.J. Crowder
// Licensed under the Creative Commons Attribution License 2.0 (UK)
// http://creativecommons.org/licenses/by/2.0/uk/
var Helper = (function(){
var toStringProblematic, // true if 'toString' may be missing from for..in
valueOfProblematic; // true if 'valueOf' may be missing from for..in

// IE doesn't enumerate toString or valueOf; detect that (once) and
// remember so makeClass can deal with it. We do this with an anonymous
// function we don't keep a reference to to minimize what we keep
// around when we're done.
(function(){
var name;

toStringProblematic = valueOfProblematic = true;
for (name in {toString: true, valueOf: true}) {
if (name == 'toString') {
toStringProblematic = false;
}
if (name == 'valueOf') {
valueOfProblematic = false;
}
}
})();

// This function is used to create the prototype object for our generated
// constructors if the class has a parent class. See makeConstructor for details.
function protoCtor() { }

// Build and return a constructor; we do this with a separate function
// to minimize what the new constructor (a closure) closes over.
function makeConstructor(base) {

// Here's our basic constructor function (each class gets its own, a
// new one of these is created every time makeConstructor is called).
function ctor() {
// Call the initialize method
this.initialize.apply(this, arguments);
}

// If there's a base class, hook it up. We go indirectly through `protoCtor`
// rather than simply doing "new base()" because calling `base` will call the base
// class's `initialize` function, which we don't want to execute. We just want the
// prototype.
if (base) {
protoCtor.prototype = base.prototype;
ctor.prototype = new protoCtor();
protoCtor.prototype = {}; // Don't leave a dangling reference
}

// Set the prototype's constructor property so `this.constructor` resolves
// correctly
ctor.prototype.constructor = ctor;

// Flag up that this is a constructor (for mixin support)
ctor._isConstructor = true;

// Return the newly-constructed constructor
return ctor;
}

// This function is used when a class doesn't have its own initialize
// function; since it does nothing and can only appear on base classes,
// all instances can share it.
function defaultInitialize() {
}

// Get the names in a specification object, allowing for toString and
// valueOf issues
function getNames(members) {
var names, // The names of the properties in 'members'
name, // Each name
nameIndex; // Index into 'names'

names = [];
nameIndex = 0;
for (name in members) {
names[nameIndex++] = name;
}
if (toStringProblematic && typeof members.toString != 'undefined') {
names[nameIndex++] = 'toString';
}
if (valueOfProblematic && typeof members.valueOf != 'undefined') {
names[nameIndex++] = 'valueOf';
}
return names;
}

// makeClass: Our public "make a class" function.
// Arguments:
// - base: An optional constructor for the base class.
// - ...: One or more specification objects containing properties to
// put on our class as members; or functions that return
// specification objects. If a property is defined by more than one
// specification object, the last in the list wins.
// Returns:
// A constructor function for instances of the class.
//
// Typical use will be just one specification object, but allow for more
// in case the author is drawing members from multiple locations.
function makeClass() {
var base, // Our base class (constructor function), if any
argsIndex, // Index of first unused argument in 'arguments'
ctor, // The constructor function we create and return
members, // Each members specification object
names, // The names of the properties in 'members'
nameIndex, // Index into 'names'
name, // Each name in 'names'
value, // The value for each name
baseValue; // The base class's value for the name

// We use this index to keep track of the arguments we've consumed
argsIndex = 0;

// Do we have a base?
if (typeof arguments[argsIndex] == 'function' &&
arguments[argsIndex]._isConstructor) {
// Yes
base = arguments[argsIndex++];
}

// Get our constructor; this will hook up the base class's prototype
// if there's a base class, and mark the new constructor as a constructor
ctor = makeConstructor(base);

// Assign the members from the specification object(s) to the prototype
// Again, typically there's only spec object, but allow for more
while (argsIndex < arguments.length) {
// Get this specification object
members = arguments[argsIndex++];
if (typeof members == 'function') {
members = members();
}

// Get all of its names
names = getNames(members);

// Copy the members
for (nameIndex = names.length - 1; nameIndex >= 0; --nameIndex) {
name = names[nameIndex];
value = members[name];
if (base && typeof value == 'function' && !value._isMixinFunction) {
baseValue = base.prototype[name];
if (typeof baseValue == 'function') {
value.$super = baseValue;
}
}
ctor.prototype[name] = value;
}
}

// If there's no initialize function, provide one
if (!('initialize' in ctor.prototype)) {
// Note that this can only happen in base classes; in a derived
// class, the check above will find the base class's version if the
// subclass didn't define one.
ctor.prototype.initialize = defaultInitialize;
}

// Return the constructor
return ctor;
}

// makeMixin: Our public "make a mixin" function.
// Arguments:
// - ...: One or more specification objects containing properties to
// put on our class as members; or functions that return
// specification objects. If a property is defined by more than one
// specification object, the last in the list wins.
// Returns:
// A specification object containing all of the members, flagged as
// mixin members.
function makeMixin() {
var rv, // Our return value
argsIndex, // Index of first unused argument in 'arguments'
members, // Each members specification object
names, // The names in each 'members'
value; // Each value as we copy it

// Set up our return object
rv = {};

// Loop through the args (usually just one, but...)
argsIndex = 0;
while (argsIndex < arguments.length) {
// Get this members specification object
members = arguments[argsIndex++];
if (typeof members == 'function') {
members = members();
}

// Get its names
names = getNames(members);

// Copy its members, marking them as we go
for (nameIndex = names.length - 1; nameIndex >= 0; --nameIndex) {
name = names[nameIndex];
value = members[name];
if (typeof value == 'function') {
value._isMixinFunction = true;
}
rv[name] = value;
}
}

// Return the consolidated, marked specification object
return rv;
}

// Return our public members
return {
makeClass: makeClass,
makeMixin: makeMixin
};
})();
Which lets us do things like this:
var Parent = Helper.makeClass(function(){
function hierarchy() {
return "P";
}
return {hierarchy: hierarchy};
});
var Child = Helper.makeClass(Parent, function(){
function hierarchy() {
return hierarchy.$super.call(this) + " < C";
}
return {hierarchy: hierarchy};
});
var GrandChild = Helper.makeClass(Child, function(){
function hierarchy() {
return hierarchy.$super.call(this) + " < GC";
}
return {hierarchy: hierarchy};
});
var gc = new GrandChild();
alert(gc.hierarchy()); // Alerts "P < C < GC"
And I believe I promised a sample mixin to help those anonymouses:
// Define our CallSuper mixin
Helper.CallSuperMixin = makeMixin(function() {
function callSuper(ref) {
var f, // The function to call
args, // Arguments to pass it, if we have any
len, // Length of args to pass
srcIndex, // When copying, the index into 'arguments'
destIndex, // When copying args, the index into 'args'
rv; // Our return value

// Get the function to call: If they pass in a function, it's the
// subclass's version so look on $super; otherwise, they've passed
// in 'arguments' and it's on arguments.callee.$super.
f = typeof ref == 'function' ? ref.$super : ref.callee.$super;

// Only proceed if we have 'f'
if (f) {
// If there are no args to pass on, use Function#call
if (arguments.length == 1) {
rv = f.call(this);
} else {
// We have args to pass on, build them up.
// Note that doing this ourselves is more efficient on most
// implementations than applying Array.prototype.slice to
// 'arguments', even though it's built in; the call to it
// is expensive (dramatically, on some platforms).
len = arguments.length - 1;
args = new Array(len);
srcIndex = 1;
destIndex = 0;
while (destIndex < len) {
args[destIndex++] = arguments[srcIndex++];
}

// Use Function#apply
rv = f.apply(this, args);
}
}

// Done
return rv; // Will be undefined if there was no 'f' to call
}

return {callSuper: callSuper};
});


Conclusion


The goal of this post is not for people to run off and start using the Helper provided here. The goal is to demonstrate a really simple, highly efficient means of implementing supercalls in these sorts of libraries, and discussing some edge cases around doing so. If you use Prototype, you might want to take a look at my patch for Prototype 1.6.1 (I have no idea whether that will make it into Prototype), which handles dynamic redefinition and such (although that patch doesn't — yet — handle mixins).

We've talked about a lot of things, so let's remind oursselves of what the mechanism is at its roots:
  • Have a "make a class" function.
  • In that function, detect that a subclass function (Child#nifty) is overriding a superclass function (Parent#nifty) and, if so, put a reference to the superclass function on the subclass function instance as a property.
  • To call a superclass function from a subclass function, authors use Function#call or Function#apply on the $super property of the subclass function instance (being sure to get the function directly, not via this). This is simplest and fastest with named functions, but possible with anonymous ones too.
  • Allow for mixins, if you're into that sort of thing (and why not, they're cool)
    Oh, and of course:
  • Profit!
Many thanks again to JDD, kangax, Allen, and others who've helped me hammer this out!

Happy Coding,

-- T.J.

No comments: