Last active
August 29, 2015 14:07
-
-
Save mytharcher/188789eaa262ac365461 to your computer and use it in GitHub Desktop.
Tiny OO inheritance of JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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