Search code examples
javascriptoopinheritanceprototype

Pick the prototype to avoid if-else


The below code snippet I found on one blogs to avoid if-else statement. This code is very modular and can be easily extended. But I am not able to get this to work.

CatModel.prototype.makeWords = function () {
    console.log('inside catmodel') 
    this.setWord('meow')
    this.sayIt()
}

DogModel.prototype.makeWords = function () {
    console.log('inside dogmodel')
    this.setWord('bark')
    this.saySomething()
}


// somewhere else
var makeWords = function (type) {
    var model = namespace[type + 'Model']
    model.makeWords()
}

makeWords('cat')

Solution

  • Presumably the CatModel and DogModel functions are declared somewhere and setWord and sayIt are also set up on their prototype object.

    You'd need to put CatModel and DogModel in an object and refer to it from namespace (which I'd recommend not calling namespace):

    var namespace = {
        CatModel: CatModel,
        DogModel: DogModel
    };
    

    Then when creating an instance, use new (you always use new with constructor functions). I'd also put the () on the call even though strictly speaking they're optional if you don't have parameters to pass:

    var makeWords = function (type) {
        var model = new namespace[type + 'Model']()
        // ---------^^^--------------------------^^
        model.makeWords()
    }