Skip to content

Instantly share code, notes, and snippets.

@mytharcher
Last active August 29, 2015 14:07
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 mytharcher/188789eaa262ac365461 to your computer and use it in GitHub Desktop.
Save mytharcher/188789eaa262ac365461 to your computer and use it in GitHub Desktop.
Tiny OO inheritance of JavaScript
function Class (proto, Super) {
// use noop function as default constructor if user not defined as in Java
var i, newClass = proto.hasOwnProperty('constructor') ? proto.constructor : function () {};
if (Super) {
var SuperHelper = function () {};
SuperHelper.prototype = Super.prototype;
// make `instanceof` could be use to check the inheritance relationship
newClass.prototype = new SuperHelper();
// fix constructor function
newClass.prototype.constructor = newClass;
// copy static members from super class to new class (not override)
for (i in Super) {
if (!newClass.hasOwnProperty(i) && Super.hasOwnProperty(i)) {
newClass[i] = Super[i];
}
}
SuperHelper = null;
}
// copy user defined prototype members back to new class
for (i in proto) {
if (proto.hasOwnProperty(i)) {
newClass.prototype[i] = proto[i];
}
}
return newClass;
}
/*
var A = Class({
constructor: function(name){
this.name = name;
}
});
var B = Class({
constructor: function (name, age) {
A.call(this, name);
this.age = age;
}
}, A);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment