mardi 18 juillet 2017

Javscript - Module design pattern

I am reviewing some design patterns in javascript. My first design pattern is module pattern. After researching a bit I build the following example:

var CarCostEstimation = (function() {

    //Let's imagine script is getting best price from different api's
    function getBestMotorCost() {

        return 3000;
    }

    function getBestChasisCost() {
        return 1000;
    }

    function getBestWheelsCost() {
        return 400;
    }

    return {
        getEstimatedCost: function() {
            var chasisCost = getBestChasisCost();
            var motorCost = getBestMotorCost();
            var wheelsCost = getBestWheelsCost();

            return chasisCost + motorCost + wheelsCost;
        }
    }

})();

var totalCost = CarCostEstimation.getEstimatedCost();
console.log(totalCost);

I have 2 doubts:

  1. If the way I am calling the "private" methods, in my public method is the correct one.

  2. If I want to add this CarCostEstimation module to another Estimation module, how would it do it?

Thanks in advance for your help.

****UPDATE****

For point 2:

var CostEstimation = (function() {

    var estimationObject;

    function sumDifferentEstimations() {
        estimationObject.getEstimatedCost();
    }

    return {
        addEstimationObjetc: function(object) {
            estimationObject = object
        },

        getTotalCost: function() {
            return sumDifferentEstimations();
        }
    }

})();

Aucun commentaire:

Enregistrer un commentaire