Make class inheritance in Javascript as easy as CoffeeScript.
class A
@name = 'apple'
class B extends A
constructor:
super()
@data = 'mydata'
To do the same thing in JS requires...
function A() {
this.name = 'apple';
}; // constructor function
function B() {
A.call(this);
this.data = 'banana';
}
B.prototype = new A();
It's hard to get the hang of.
The instance assigned into B.prototype becomes the object to be copied
into new instances of B.
Using A.call(this)
in the constructor is funky.
Same with B.prototype.method.call(this)
to call super class methods.
I had two Aha! moments understanding prototype based inheritance:
- Only functions (AKA constructors) have prototypes. Instances don't have them.
function X() {}
always runs beforevar X = function();
(duh, right?)
- Simpler syntax for
B.prototype = new A();
- Avoid (preferably with a
super
method):A.call(this)
// call super constructorA.prototype.method.call(this)
// call super's method
- Copy class data and methods (on class, not instance)
- Preserve instanceof operator
- CoffeeScript
__extends
- not quite librifiable since generates code - node's
util.inherits
- doesn't copy data, just functions - lodash
_.create
- half of the puzzle still requires knowledge of prototype - John Resig's
Class.extend
- Winner!- I added a couple lines to copy class data + methods on to the derived class (inspired by CoffeeScript __extend)