javascript-私有/公共成员/函数

javascript-私有/公共成员/函数,javascript,Javascript,我正在测试使用var、this和global声明变量/方法时会发生什么,我想知道最好的方法是什么。我有以下代码: myApp.ConfirmationWindow = function (temptype) { var _type = temptype; this.type = temptype; type2 = temptype; this.getType = function () { return _type; } th

我正在测试使用var、this和global声明变量/方法时会发生什么,我想知道最好的方法是什么。我有以下代码:

myApp.ConfirmationWindow = function (temptype) {
    var _type = temptype;
    this.type = temptype;
    type2 = temptype;

    this.getType = function () {
        return _type;
    } 

    this.showConfirmationWindow = function (message) {
        var a = _type;  //valid
        var b = this.type; //valid
        var c = type2; // valid
        var d = this.getType(); // valid

        this.showWindow(message);
        showWindow2(message);
        showWindow3(message);
    }

    this.showWindow = function (message) {
      var a = _type;  //valid
      var b = this.type; //valid
      var c = type2; // valid  
      var d = this.getType(); // valid
  }

  showWindow2 = function (message) {
      var a = _type;  //valid
      var b = this.type; //invalid
      var c = type2; // valid
      var d = this.getType(); // invalid
  }

  var showWindow3 = function (message) {
      var a = _type;  //valid
      var b = this.type; //invalid
      var c = type2; // valid
      var d = this.getType(); // invalid
  }
};
用法: myApp.ConfirmationWindow1=新的myApp.ConfirmationWindow(1); myApp.ConfirmationWindow1.showConfirmationWindow('你确定吗?')


目标是使类型变量和showWindow函数私有。从我的例子中可以看出,有很多方法可以实现这一点。推荐的方法是什么?

您可以在示例中使用var模式隐藏您的私有代码。要公开私有变量,可以使用实例函数。如果将它们设置为全局或函数的成员,则它们是公共的

myApp.ConfirmationWindow = function (temptype) {
    var _type = temptype;
    this.getType = function () {
        return _type;
    } 
    var showWindow = function (message) {
      var d = _type
    }
    this.showConfirmationWindow = function (message) {
        showWindow(message);
    }  
};

我建议使用module-reveal模式,将私有变量保存在。下面是一个通用示例。您可以阅读有关以下内容的更多信息:

让myVar=true;
让模块=(函数(){
//这些是私有变量(在闭包中)
让_privateVariable='private',
_privateFunction=函数(){
警报(_privatevaluate);
};
让_publicVariable='public',
_publicFunctionGet=函数(){
警报(_公共变量);
},
_publicFunctionSet=函数(值){
_公共变量=值;
};
//提供公共函数来设置私有变量
返回{
publicFunctionSet:_publicFunctionSet,
publicFunctionGet:\u publicFunctionGet
};
})();
module.publicFunctionSet(“新公共”);
module.publicFunctionGet();

警报(myVar);//可用于代码的其他部分
,因此换句话说,任何var成员都是私有的,而任何使用它的成员都是私有的public@user2769810这实际上取决于您的代码,我对我的答案进行了编辑,显示var/let可能不是私有的,并且在函数外部可见。看起来模块显示模式更具可读性,而且比使用奥尔曼教授的模式更具可扩展性。在哪种情况下,人们会使用这两种模式?竖起大拇指查看模块显示模式和let语法;在这之前我都不知道@用户2769810我很高兴我的答案喜欢它,如果你觉得我的答案有用,请不要忘记单击向上投票,并使用向上箭头图标批准我的答案,并在其左侧打勾。感谢您的合作和愉快的编码:)