了解javascript

时间:2015-07-03 19:51:13

标签: javascript

我在JavaScript方面不是很好。所以当我现在看到一段代码时,很多区域都不清楚。所以有人请帮助我理解。

我知道以下人们宣称他们的模块

var Module = (function () {
  var privateMethod = function () {
    //A Private Method
    var privatemember; // scope is only private method
  };
  return {
    publicMethod: function () {
      //you can call private method here.
    }
  };
})();

Module.publicMethod(); //works

刚才我看到了另一个不同的模块模式代码,如下所示:使用了knockout.js。

var HMS = HMS || {};

$(function () {

    HMS.PatientModel = function () {
        this.Patient_Name = ko.observable();
        this.Patient_Address = ko.observable();
    };

    HMS.PatientViewModel = function () {
        var patient = ko.observable(),
        loadPatient = function () {
            var newModel = new HMS.PatientModel();
            newModel.Patient_Name("Premkumar");
            patient(newModel);
        };
        return {
            patient: patient,
            loadPatient: loadPatient
        };
    } ();


    HMS.PatientViewModel.loadPatient();

    ko.applyBindings(HMS.PatientViewModel);

});

1)这段代码var HMS = HMS || {};是什么?

2)见$(function () {}) ();

为什么模块没有特定的名称。看到我的第一个代码,我就像这样给我的模块命名var Module = (function () {}) ()

3)在模块内部代码中,每个函数名称都以HMS开始.............为什么像HMS.PatientModel = function () { };

请帮助我理解第二套代码点。感谢

2 个答案:

答案 0 :(得分:1)

var HMS = HMS || {}; 

该表达式将var HMS定义为HMS或空对象(如果未定义)是

的简写
if(HMS) {
  var HMS = HMS;
} else {
  var HMS = {};
}

2)您正在从IIFE创建对象

如果它们不存在,它们是声明和空对象,并且一旦执行了下面的函数,就用方法/函数进行装饰。 与此相同:

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

3)这就是他们在函数中使用HMS的原因。

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

您应该阅读ClosuresIIFEHow to “properly” create a custom object in JavaScript?

关闭的示例和简短说明:

闭包是指您可以访问不在函数词法范围内的变量。例如,在另一个函数内声明的函数将有权访问父变量。

例如:

(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

答案 1 :(得分:1)

  

1)这段代码是什么变量HMS = HMS || {}; ?

如果HMS未定义,则HMS应等于空对象,否则按原样使用HMS(在您的情况下,HMS是对象)。

  

2)看到这个$(function(){})();

它被称为IIFE

  

3)为什么喜欢HMS.PatientModel = function(){};

HMS是一个对象,只是添加其属性值。价值可能是任何东西。

  

4)从另一个答案的评论中,为什么他们没有定义模块名称?

他们已将模块名称定义为Module。见var Module = (function(){}());