- To track subclasses
- To reinitialize class-level variables in a subclass that were defined in a parent class.
- To have control over what happens when something is subclassed
These are the ones off the top of my head, more use cases are elaborated on here:
class Model
class Parent extends Model
class Child extends Parent
Model.subclasses #=> [Parent, Child]
This makes metaprogramming possible. For one example, I can track dependencies, so if a file changes, and it has dependent subclasses, I can reload them in node.js. Another, I can automatically validate that a type
property is valid given a model when it's saved, b/c we know all possible subclasses. Plus, in Ruby/Rails, there's a million places you have an included
or extended
hook where being able to store metadata about this relationship gives you a lot of power.
class Attribute
constructor: (name, options = {}) ->
@name = name
@options = options
class Model
@attributes: {}
@attribute: (name, options) ->
@attributes[name] = new Attribute(name, options)
class Parent extends Model
@attribute "role", default: "guest"
class Child extends Parent
# I don't want this to happen:
Child.attributes.role.options.customProperty = true
console.log Parent.attributes.role.options
# {"default":"guest","customProperty":true}
# instead, I want to clone all `attributes` in the subclass,
# i.e. I want to clone all class-level objects in the subclass
Ember.js has a more robust implementation of extend
, where it properly adds mixins and such to the subclass. Just being able to do this would open up a ton of possibilities.