Created
August 28, 2012 02:03
-
-
Save timhall/3494261 to your computer and use it in GitHub Desktop.
Javascript inheritance (slight additions to backbone's implementation)
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
// Subclass given parent class and extend with prototype and static properties | |
// (inherits helper from Backbone.js) | |
var inherits = function (parent, protoProps, staticProps) { | |
var child; | |
if (protoProps && protoProps.hasOwnProperty('constructor')) { | |
child = protoProps.constructor; | |
} else { | |
child = function () { parent.apply(this, arguments); }; | |
} | |
_.extend(child, parent); | |
var ctor = function () { }; | |
ctor.prototype = parent.prototype; | |
child.prototype = new ctor(); | |
if (protoProps) _.extend(child.prototype, protoProps); | |
if (staticProps) _.extend(child, staticProps); | |
child.prototype.constructor = child; | |
child.__super__ = parent.prototype; | |
return child; | |
}; | |
// Wrapper for inherits to be applied to Class | |
var extend = function (constructor, protoProps, classProps) { | |
// (This is the primary departure from backbone's implementation) | |
// Include constructor argument to make using KnockoutJS's typical | |
// viewmodel definition much simpler to use | |
if (_.isFunction(constructor)) { | |
// Define constructor in prototype properties, if given | |
protoProps = protoProps || {}; | |
protoProps.constructor = constructor; | |
} else if (constructor && !classProps) { | |
// If constructor is not a function, but exists | |
// and classProps aren't given, | |
// assume no-constructor input is being used | |
classProps = protoProps; | |
protoProps = constructor; | |
} | |
var child = inherits(this, protoProps, classProps); | |
child.extend = this.extend; | |
child.inherit = this.inherit; | |
return child; | |
}; | |
// Convenience for calling parent constructor | |
var inherit = function (child) { | |
this.apply(child, Array.prototype.slice.call(arguments, 1)); | |
return child; | |
}; | |
// Extendable method for adding extend and inherit functions to Class | |
var extendable = function (Class) { | |
Class.extend = extend; | |
Class.inherit = inherit; | |
return Class; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment