Skip to content

Instantly share code, notes, and snippets.

@cgddrd
Last active August 29, 2015 14:27
Show Gist options
  • Save cgddrd/e0c790a25d4ad5d642f8 to your computer and use it in GitHub Desktop.
Save cgddrd/e0c790a25d4ad5d642f8 to your computer and use it in GitHub Desktop.
Javascript - Abstract Class Design Pattern
var testChildClass = new ChildClass(5, "A child class property!");
console.log(testChildClass.basePropertyThree); // '5'
console.log(testChildClass.anotherProperty); // 'A child class property!'
console.log(testChildClass.baseFunction()); // '7'
testChildClass.childFunction('Hello world!'); // 'Hello world!'
function BaseClass(param1) {
if (this.constructor === BaseClass) {
throw new Error("Can't instantiate abstract class!");
}
this.basePropertyOne = "Property1";
this.basePropertyTwo = 2;
this.basePropertyThree = param1;
}
BaseClass.prototype.baseFunction = function() {
return this.basePropertyTwo + this.basePropertyThree;
}
function ChildClass(parameterToBase, normalParameter) {
// We want to use 'apply', and not 'call' for this.
// See: http://stackoverflow.com/a/1986909/4768230 for why.
BaseClass.apply(this, arguments);
// 'parameterToBase' will be sent down to the 'base' class.
this.anotherProperty = normalParameter;
}
ChildClass.prototype = Object.create(BaseClass.prototype);
ChildClass.prototype.constructor = ChildClass;
ChildClass.prototype.childFunction = function(string) {
console.log(string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment