如何在JavaScript中实现Module设计模式

时间:2017-07-18 21:49:40

标签: javascript design-patterns

我正在审核JavaScript中的一些设计模式。我的第一个设计模式是模块模式。在研究了一下后,我构建了以下示例:

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);

我有两个疑问:

  1. 如果我打电话给"私人"方法,在我的公共方法中是正确的。

  2. 如果我想将此CarCostEstimation模块添加到另一个Estimation模块,它会怎么做?

  3. 对于第2点:

    var CostEstimation = (function() {
    
        var estimationObject;
    
        function sumDifferentEstimations() {
            estimationObject.getEstimatedCost();
        }
    
        return {
            addEstimationObjetc: function(object) {
                estimationObject = object
            },
    
            getTotalCost: function() {
                return sumDifferentEstimations();
            }
        }
    
    })();
    

1 个答案:

答案 0 :(得分:2)

定义功能的另一种方法。 (我也使用了一些ES6语法)

    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); 

要将您的功能导出为模块,您可以使用ES6中的导出语句并使用导入语句导入模块

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