Observe the following Coffeescript:
1 2 3 4 5 6 7 8 9 10
Here, take a look at the generated JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
But… what is that mess of generated code at the top? The first part is pretty
clear - just copy object properties from one “class” to another, so that (for example)
Ninja.belt will be inherited by Ronin.belt. And assigning a
__super pointer to
the parent class is straightforward. But what is that “constructor” code?
Why not just point the “subclass” prototype to the parent prototype?
It turns out this approach is the cleanest means of maintaining the prototype chain
across functions. Since there’s only one prototype object for any function, simply
Ronin.prototype=Ninja.prototype will share a single object instance, so
adding properties to Ronin’s prototype would actually also add properties to Ninja’s
prototype – they’d be the same object instance. By creating an intermediary
object, the prototype chain is kept intact while breaking any chance for incorrectly
point to the “creator” function, whose initial value is determined by the object’s
prototype. The intermediary object (which serves as the
child’s prototype) thus gets a pointer back to the appropriate function.