Simple 'extend' helper for inheritance and subclassing
MIT License
Simple 'extend' helper for inheritance and subclassing. Adapted from Backbone.js's Model.extend and CoffeeScript. This works like simple-extend, except this does not have any dependencies.
Assign it to your base class's .extend
:
function Shape() { ... }
Shape.extend = require('simpler-extend');
Then use it to subclass:
var Circle = Shape.extend({
getArea: function () {
return this.width * this.height;
}
});
You can also add a constructor as constructor
:
var Circle = Shape.extend({
constructor: function () { ... }
});
Calling methods from the base class:
var Circle = Shape.extend({
getArea: function () {
var super = Shape.prototype.getArea.apply(this, arguments);
return super * Math.PI;
}
});
See Backbone.js's Model.extend documentation for more details.
To create an extendable class, you can use any kind of JavaScript function with a prototype (a "class"):
function Shape(width, height) {
this.width = width;
this.height = height;
}
Shape.prototype.getArea = function () {
return this.width & this.height;
};
// Allow subclassing `Shape`
Shape.extend = require('simpler-extend');
simpler-extend
can be used with ES6 classes. The only advantage of using this over ES6's native inheritance is that it will support legacy ES5 engines like old IE's (which Babel doesn't support).
/* es6 */
class Shape {
...
}
Shape.extend = require('simpler-extend');
Subclassing can use the ES6 object syntax:
let Circle = Shape.extend({
getArea() {
var super = Shape.prototype.getArea.apply(this, arguments);
return super * Math.PI;
},
getCircumference() {
...
}
})
simpler-extend © 2015+, Rico Sta. Cruz. Released under the MIT License. Authored and maintained by Rico Sta. Cruz with help from contributors (list).
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz