开发者

The private method in javascript

In my applica开发者_StackOverflowtion,I have to build a standalone lib for other people use,so I create new object like this:

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=....
}

This will make the paresData function to the user.

Now,I wonder which is better?


If you want actually private data/methods you should be using closures better.

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 now only has the two "public" functions, login and loadDataFromServer you can still access the "private" functions from the public functions but you cannot directly access any of the "private" methods MyService._login('test','pass'); will fail but MyService.login('test','pass'); will work. See this example http://jsfiddle.net/EXrDW/


There is no "better" answer, only what you feel more comfortable with. What a lot of people seem to have adopted is the practice of putting underscores in front of methods that shouldn't be accessed by users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜