« Back to Index

Polymorphism using if condition in JavaScript

View original Gist on GitHub

If Conditional Polymorphism Example.js

function test (condition) {
    if (condition === "A") {
        // lots of code related to "A" here
    } else if (condition === "B") {
        // lots of code related to "B" here
    } else if (condition === "C") {
        // lots of code related to "C" here
    }
}
 
test('A');
test('B');
test('C');

// CONVERT THAT TO...

var A = {
    doTheThing: function(){
        lots of code related to "A" here
    }
}

var B = {
    doTheThing: function(){
        lots of code related to "B" here
    }
}

var C = {
    doTheThing: function(){
        lots of code related to "C" here
    }
}

function test (condition) {
    condition.doTheThing();    
}
 
test(A);
test(B);
test(C);