官术网_书友最值得收藏!

Re-factoring to a more modularized approach

Let's consider re-factoring the two functions that we looked at previously and putting them together in a more specialized package (class or module) called, CalculationHandler, as shown below:

function CalculationHandler(){
  CalculationHandler.result = null;
}

CalculationHandler.doAddition = function(num1, num2){
  return num1 + num2;
};

CalculationHandler.doSubtraction = function(num1, num2){

  if(num1 > num2){
    CalculationHandler.result = num1 - num2;

  }else{
    CalculationHandler.result = num2 - num1; 
  }
  return CalculationHandler.result;

};

console.log(CalculationHandler.doAddition(3,2)); // displays 5
console.log(CalculationHandler.doSubtraction(3,2)); // displays 1

As you can see in this "module" (and I use the term loosely here; you will see why in later chapters), I am using a function object and adding properties (methods) to this object. This methods do specialized tasks related to the overall functionality of the object (module), such as addition and subtraction.

Note

A note about our module here

If you are more experienced in JavaScript programming, you are probably thinking that the way I have created this module is probably not the best way to create a real module in JavaScript, and you are right! But for now, the big idea here is that any piece of code that does a specialized task can be tagged as a module, for the most part.

However, there are certainly better ways to write more robust and extensible modules in JavaScript. For instance, creating a module can be accomplished much better by using the Module Design Pattern, which we will get to explore a lot further in later chapters of this book.

主站蜘蛛池模板: 台北市| 乌鲁木齐县| 东宁县| 武川县| 土默特右旗| 洱源县| 安乡县| 葵青区| 丹巴县| 太白县| 黑水县| 沂水县| 赤峰市| 大埔县| 邓州市| 东山县| 南开区| 德令哈市| 阿合奇县| 中山市| 中阳县| 长海县| 吴堡县| 望谟县| 莱阳市| 海丰县| 天峻县| 平乡县| 于都县| 南华县| 博野县| 姜堰市| 恩平市| 聂拉木县| 宜兰市| 镇安县| 涪陵区| 平安县| 巴彦淖尔市| 都昌县| 即墨市|