Last active
August 29, 2015 14:27
-
-
Save cgddrd/e0c790a25d4ad5d642f8 to your computer and use it in GitHub Desktop.
Javascript - Abstract Class Design Pattern
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
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!' |
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
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; | |
} |
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
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