Skip to content

Instantly share code, notes, and snippets.

@joeworkman
Created December 6, 2017 19:52
Show Gist options
  • Save joeworkman/57489828370625a9628330dabb7581c6 to your computer and use it in GitHub Desktop.
Save joeworkman/57489828370625a9628330dabb7581c6 to your computer and use it in GitHub Desktop.
A JavaScript inheritance model
(function() {
// Parent Class
this.ClassA = function() {
var defaults = {
setting1: null,
setting2: 'hello',
}
// Create options by extending defaults with the passed in arugments
if (typeof arguments[0] === "object") {
this.options = this.extend(defaults, arguments[0]);
}
}
// This is a utility method for extending an options object
ClassA.prototype.extend = function(source, properties){
var property;
for (property in properties) {
if (properties.hasOwnProperty(property)) {
source[property] = properties[property];
}
}
return source;
}
// This is a utility method for merging 3 option sets into one
ClassA.prototype.mergeOptions = function(global,defaults,local){
var options = {};
// Merge global options with defaults. Defaults wins
if (typeof global === "object") {
options = this.extend(defaults, global);
}
// Merge options with local. Local wins
if (typeof local === "object") {
options = this.extend(options,local);
}
return options;
}
// Test Log method
ClassA.prototype.log = function(){
console.log('This is Class A');
}
}());
(function() {
// Child Class
this.ClassB = function() {
// Inheritance to Class A
ClassA.call(this);
// Define option defaults
var defaults = {
setting1: 'yo yo',
setting2: true,
}
// this.options is populated from ClassA.call()
// merge those with defaults and arguments passed
this.options = ClassA.prototype.mergeOptions(this.options,defaults,arguments[0]);
}
// Inheritance to Class A - this gets all prototypes
ClassB.prototype = Object.create(ClassA.prototype);
ClassB.prototype.log = function(){
console.log('This is Class B');
}
}());
//-----------------------------------------------
// Implementation
//-----------------------------------------------
var b = new ClassB({'setting1':'Caio'});
b.log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment