简体   繁体   中英

How to implement the Module design pattern in JavaScript

I am reviewing some design patterns in JavaScript. My first design pattern is the module pattern. After researching a bit I built 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 two 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?

For point 2:

var CostEstimation = (function() {

    var estimationObject;

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

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

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

})();

Another way to define your functions. (I'm also using some ES6 syntax)

    const CarCostEstimation = function() {
      return {
        getBestMotorCost: () => 3000,
        getBestChasisCost: () => 1000,
        getBestWheelsCost: () => 400,
        getEstimatedCost: function() {
          const chasisCost = this.getBestChasisCost();
          const motorCost  = this.getBestMotorCost();
          const wheelsCost = this.getBestWheelsCost();

          return chasisCost + motorCost + wheelsCost;
        }
      }
    }();

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

To export your function as a module, you could use the export statement from ES6 and import your module using the import statement

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM