2017-03-07 31 views
2

我正在测试当我用var,this和global声明变量/方法时发生了什么,并且想知道什么是最好的方法。我有以下代码:javascript - private/public members/functions

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('Are you sure?');

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

回答

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

+0

该模块的拇指显示模式和let语法;在这之前我都不知道! – user2769810

+0

@ user2769810我很高兴我的答案喜欢它,如果您发现我的答案有用,请不要忘记单击upvote并使用向上箭头图标批准我的答案,并在其左侧打勾。感谢您的协作和快乐编码:) – GibboK

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); 
    } 
}; 
+0

所以,换句话说,这是一个变种是私人使用,这是公众 – user2769810

+0

@ user2769810它实际上取决于中的任何成员,任何成员的代码,我对我的答案进行了编辑,表明var/let可能不是私有的,并且在函数外可见 – GibboK

+0

看起来模块显示模式比使用Allman教授模式更具可读性,更具可扩展性。在哪种情况下,一个人会使用哪种模式? – user2769810