原型编程——javascript中的私有方法

prototype programming - The private method in javascript

本文关键字:有方法 javascript 编程 原型      更新时间:2023-09-26

在我的应用程序中,我必须构建一个供其他人使用的独立库,所以我创建了这样的新对象:

function MyService(){
  //xxxxxxx...
}
MyService.prototype.login=function(name,pass){
  //here 
}
MyService.prototype.LoadDataFromServer(){
  //use the ajax get data from server,when get the data,I will eval them :
  var data=parseData(request.responseText);
  //now,the parseData is a private method which should not be exposed to the user,but it need the reference of the MyService object(this),so I have to use the following code:
  var this_ref=this;
  function parseData(res){
    this_ref.xxxx=.....
  }
}

MyService.prototype.parseData=function(res){
  this.xxxxx=....
}

这将使parsdata函数为用户。

现在,我想知道哪个更好?

如果你想要真正私有的数据/方法,你应该更好地使用闭包。

var MyService = (function() {
    // define "private" methods
    var _login = function(name, pass) {
          ...
        },
        _loadDataFromServer = function() {
            ....
        },
        _parseData = function(res) {
            ...
        };
     //return "public" methods
     return {
         login: _login,
         loadDataFromServer: _loadDataFromServer
     };
}()); // execute function immediately

MyService现在只有两个"公共"函数,loginloadDataFromServer,您仍然可以从公共函数访问"私有"函数,但您不能直接访问任何"私有"方法,MyService._login('test','pass');将失败,但MyService.login('test','pass');将工作。参见此示例http://jsfiddle.net/EXrDW/

没有"更好"的答案,只有你觉得更舒服的答案。许多人似乎采用的做法是在用户不应该访问的方法前面加下划线。