Skip to content

Instantly share code, notes, and snippets.

@abernier
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abernier/decf360c677a54aa415c to your computer and use it in GitHub Desktop.
Save abernier/decf360c677a54aa415c to your computer and use it in GitHub Desktop.
inherit.js

Classical inheritance for constructors.

INSTALL

Client-side

<script src="inherit.js"></script>

Server-side

npm install https://gist.github.com/abernier/decf360c677a54aa415c/download
var inherit = require('inherit');

Usage

function A() {}
A.prototype.foo = function () {};

function B() {
  B.uber.constructor.apply(this, arguments);
}
inherit(B, A);
B.prototype.foo = function () {
  this.constructor.uber.foo.apply(this, arguments);
}

NB:

  • B.uber references to A.prototype
  • classically, you can access the ctor from prototype's methods thanks to constructor property.
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1,initial-scale=1,user-scalable=no">
</head>
<body>
<script src="inherit.js"></script>
<script style="display:block; white-space:pre; font-family:monospace;">
var inherit = this.inherit || require('inherit');
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function (meters) {
alert(this.name + ' moved ' + meters);
}
function Snake() {
Snake.uber.constructor.apply(this, arguments); // borrow parent's constructor
}
inherit(Snake, Animal); // Snake.uber = Animal.prototype
Snake.prototype.move = function () {
alert('Slithering...');
this.constructor.uber.move.call(this, 5); // borrow parent's move method
}
var kaa = new Snake('Kaa');
kaa.move();
</script>
</body>
</html>
// Inheritance utility (see: http://coffeescript.org/#try:class%20A%0Aclass%20B%20extends%20A)
function inherit(child, parent) {
// shallow copy own properties
for (var key in parent) {
if (parent.hasOwnProperty(key)) {
child[key] = parent[key];
}
}
function ctor() {this.constructor = child;}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.uber = parent.prototype; // keep a reference to parent's prototype into child.uber
return child;
};
// Exports
this.inherit = inherit;
if (typeof module !== "undefined" && module !== null) {
module.exports = this.inherit;
}
{
"name": "inherit",
"version": "0.0.0",
"description": "Classical inheritance for constructors.",
"main": "inherit.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/decf360c677a54aa415c.git"
},
"author": "Antoine BERNIER (abernier)",
"license": "ISC"
}
@abernier
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment