javascript - 私人/公共成员/职能

时间:2017-03-07 19:32:05

标签: javascript

我正在测试当我使用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 = new myApp.ConfirmationWindow(1);     myApp.ConfirmationWindow1.showConfirmationWindow('你确定吗?');

目标是将type变量和showWindow函数设为私有。从我的示例中可以看出,有很多方法可以实现这一点。推荐的方式是什么?

2 个答案:

答案 0 :(得分:1)

我建议使用模块显示模式,将私有变量保存在closure中。下面是一个通用示例。您可以阅读有关revealing pattern here

的更多信息



let myVar = true;
let module = (function() {
  // these are private variables (in a closure)
  let _privateVariable = 'private',
      _privateFunction = function() {
          alert(_privateVariable);
      };
  let _publicVariable = 'public',
      _publicFunctionGet = function() {
          alert(_publicVariable);
      },
      _publicFunctionSet = function(value) {
         _publicVariable = value;
      };
  // provide public functions to set the private variables
  return {
      publicFunctionSet: _publicFunctionSet,
      publicFunctionGet: _publicFunctionGet
  };
})();

module.publicFunctionSet('new public');
module.publicFunctionGet();
alert(myVar); // available to other part of your code




答案 1 :(得分:0)

您可以使用示例中的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);
    }  
};
相关问题