-
-
Save PifyZ/9190225 to your computer and use it in GitHub Desktop.
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
// 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