Skip to content

Instantly share code, notes, and snippets.

@PifyZ
Forked from dalgard/Class.js
Created February 24, 2014 15:19
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 PifyZ/9190225 to your computer and use it in GitHub Desktop.
Save PifyZ/9190225 to your computer and use it in GitHub Desktop.
// The base constructor (can be left empty, but a nice boilerplate might look like this)
function Class(properties) {
if (properties) {
// Add properties to the instance
Object.getOwnPropertyNames(properties).forEach(function (property_name) {
var descriptor = Object.getOwnPropertyDescriptor(properties, property_name);
Object.defineProperty(this, property_name, descriptor);
}, this);
}
}
// Extensible constructors pattern inspired by Backbone.js
Class.extend = function (prototype) {
var constructor;
// Use constructor function from new prototype or from superclass
if (prototype && prototype.hasOwnProperty("constructor") && typeof prototype.constructor === "function") {
constructor = prototype.constructor;
delete prototype.constructor; // This property is handled further down
}
else {
var self = this;
constructor = function Subclass() { return self.apply(this, arguments); };
}
// Set up the prototype chain
constructor.prototype = Object.create(this.prototype);
// Locked down references
Object.defineProperties(constructor.prototype, {
"constructor": { value: constructor },
"super": { value: this.prototype }
});
if (prototype) {
// Add extended prototype properties to the subclass
Object.getOwnPropertyNames(prototype).forEach(function (property_name) {
var descriptor = Object.getOwnPropertyDescriptor(prototype, property_name);
Object.defineProperty(constructor.prototype, property_name, descriptor);
});
}
// Add extend capability and reference to super constructor
constructor.extend = this.extend;
constructor.super = this;
return constructor;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment