Skip to content

Instantly share code, notes, and snippets.

@fdjones
Last active April 21, 2018 10:00
Show Gist options
  • Save fdjones/a54a57b94d348a50fe79de94f23b077c to your computer and use it in GitHub Desktop.
Save fdjones/a54a57b94d348a50fe79de94f23b077c to your computer and use it in GitHub Desktop.
// NOT polymorphism
const obj1 = {
a: 'a',
}
const obj2 = {
a: 'b'
}
let objArray = [obj1, obj2];
objArray.forEach(obj => {
if (obj.a === 'a') {
console.log('a is equal to a!');
} else if (obj.a === 'b') {
console.log('a is equal to b!');
}
});
//Polymorphism
let BaseObj = function(a) {
this.a = a;
}
BaseObj.prototype.showA = function() {
console.log(`a is an ${this.a}`);
}
let DerivedObj1 = function(b) {
this.b = b;
}
DerivedObj1.prototype = new BaseObj();
DerivedObj1.prototype.showA = function() {
console.log('show some stuff about object 1');
}
let DerivedObj2 = function(b) {
this.b = b;
}
DerivedObj2.prototype = new BaseObj();
DerivedObj2.prototype.showA = function() {
console.log('show some stuff about object 2');
}
const obj1 = new DerivedObj1('c', 'd');
const obj2 = new DerivedObj2('e', 'f');
let objArray = [obj1, obj2];
objArray.forEach(obj => {
obj.showA();
});
// In the polymorphism example, we could create an arbitrary amount of new DerivedObject's and we don't ever have to go
// back into our forEach and alter the existing code to now check for another condition. It may not seem like such a big
// deal with this trivial example, but suppose you needed to create 10,000 objects each with their own unique showA() method
// - that would be one hell of an if-else block.
// It should be noted that Javascript's type system has no notion of polymorphism.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment