Prototypal Super
Super in Prototypal inheritance
by sym3tri
HTML
<html>
<body>
<div id="out"></div>
</body>
</html>
JavaScript
function print(msg) {
document.getElementById('out').innerHTML += msg + '<br>';
}
// all objects must inherit from Base to get the supr functionality
var Base = {
get supr() {
return Object.getPrototypeOf(this);
}
};
Shape = Object.create(Base);
Shape.name = null;
Shape.color = 'transparent',
Shape.init = function(name) {
this.name = name || 'shape';
};
Shape.getArea = function () {
return 'unable to calculate area';
};
Shape.setColor = function(color) {
this.color = color;
};
Shape.describe = function () {
print('I am a: ' + this.name);
print('color: ' + this.color);
print('area: ' + this.getArea());
print('-----');
};
Shape.init();
Shape.describe();
var Square = Object.create(Shape);
Square.init = function (sideLength) {
// this is the same as:
// Object.getPrototypeOf(this).init.call(this, 'square');
this.supr.init('square');
this.sideLength = sideLength;
};
Square.getArea = function () {
return this.sideLength * this.sideLength;
};
Square.init(2);
Square.setColor('blue');
Square.describe();
var Circle = Object.create(Shape);
Circle.init = function (radius) {
this.radius = radius;
this.supr.init('circle');
};
Circle.getArea = function () {
return this.radius * this.radius * Math.PI;
};
Circle.init(3);
Circle.setColor('yellow');
Circle.describe();