Understanding module design pattern in javascript

后端 未结 2 1082
-上瘾入骨i
-上瘾入骨i 2021-01-17 03:41

I am not very good in JavaScript. so when I saw a block of code now then many area is not clear. So someone please help me to understand.

I know this below way peopl

2条回答
  •  盖世英雄少女心
    2021-01-17 04:10

    var HMS = HMS || {}; 
    

    that expression defines the var HMS to HMS or empty object if it is not defined is a short hand for

    if(HMS) {
      var HMS = HMS;
    } else {
      var HMS = {};
    }
    

    2) You are creating an object from an IIFE

    They are declaring and empty object if it does not exist, and decorating it with the methods/functions once the function below its executed. is the same as this:

    var HMS = {
       PatientModel : function () {},
       PatientViewModel : function () {}, 
    }
    

    3) And that is why they use HMS inside the function.

    var HMS = {};
    HMS.PatientModel = function() {};
    HMS.PatientViewModel = function() {};
    

    You should read about Closures, IIFE, and How to “properly” create a custom object in JavaScript?

    Sample and short explanation of closure:

    A closure is when you have access to variables that are not in the lexical scope of the function For example, a function declared inside another function, will have access to the parent variables.

    eg:

    (function(){
        var a = 1;
    
        function mainFunction() {
    
            function innerFunction() {
                var b = 2
    
                function subFunction() {
                    console.log(a); //We have access to "a" here.
                    console.log(b); //We have access to "b" here.
                }
    
               subFunction();
            }
    
    
            innerFunction();
            console.log(a); //We have access to "a" here.
            console.log(b); //We dont have access to "b" here. //error
        }
        mainFunction();
    
    })();
    console.log(a);  //We dont have access to "a" here. //error
    

提交回复
热议问题