Understanding module design pattern in javascript

后端 未结 2 1049
-上瘾入骨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 03:55

    1) what is this code var HMS = HMS || {}; ?

    If HMS is undefined HMS is to be equal to an empty object otherwise use HMS as is (in your case HMS is an object).

    2) see this $(function () {}) ();

    It's called IIFE.

    3) why like HMS.PatientModel = function () { };

    HMS is an object and just adding its property with value. Value may be anything.

    4) From your comment in another answer, why they didn't define module name?

    They have defined the module name as Module. See var Module = (function(){}());

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题