Created
March 2, 2013 13:06
-
-
Save Sljubura/5070887 to your computer and use it in GitHub Desktop.
Class inheritance sugar
This file contains hidden or 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
// Pattern to avoid inheritance via prototype | |
var klass = function (Parent, props) { | |
var Child, Proxy, i; | |
Child = function () { | |
if (Child.uber && Child.uber.hasOwnProperty("__construct")) { // Check if Child has own constructor in context of superclass | |
Child.uber.__construct.apply(this, arguments); | |
} | |
if (Child.prototype.hasOwnProperty("__construct")) { // Check if Child has own constructor | |
Child.prototype.__construct.apply(this, arguments); | |
} | |
Parent = Parent || Object; | |
Proxy = function () {}; | |
Proxy.prototype = Parent.prototype; // Set Proxy | |
Child.prototype = new Proxy(); // Inherit from Parent via Proxy | |
Child.uber = Parent.prototype; // Allow access to Parent via superclass | |
Child.prototype.constructor = Child; // Set Child constructor to point to itself | |
for (i in props) { | |
if (props.hasOwnProperty(i)) { | |
Child.prototype[i] = props[i]; | |
} | |
} | |
}; | |
return Child; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment