原型编程——javascript中的私有方法
prototype programming - The private method in javascript
在我的应用程序中,我必须构建一个供其他人使用的独立库,所以我创建了这样的新对象:
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
现在只有两个"公共"函数,login
和loadDataFromServer
,您仍然可以从公共函数访问"私有"函数,但您不能直接访问任何"私有"方法,MyService._login('test','pass');
将失败,但MyService.login('test','pass');
将工作。参见此示例http://jsfiddle.net/EXrDW/
没有"更好"的答案,只有你觉得更舒服的答案。许多人似乎采用的做法是在用户不应该访问的方法前面加下划线。
相关文章:
- 是否有任何JavaScript UI组件可以显示字符串之间的差异
- 是否有任何Javascript函数从指定的索引中进行正则表达式匹配
- 是否有一个javascript库来解析简单的查询
- 我制作html网站的一小部分——我有一个javascript部分
- 可能有一个javascript和php的配置文件
- 有没有javascript循环的替代方案
- 我有一个javascript类和该类的对象,我想将该对象存储在本地存储中并检索它
- 是否有一个 JavaScript 加载器可以将套接字的数量限制为 1 或 2
- 有没有javascript或flash项目可以在线编辑音频
- 是否有一个Javascript函数可以使代码在运行时延迟
- 有没有JavaScript方法来做file_get_contents()
- 是否有返回javascript树映射json内部其他数据的方法
- 是否有任何JavaScript方法可以复制oracle的ADD_MONTH()功能?
- 是否有一个JavaScript/css的方法,使同步滚动区域类似于"meld"
- 是否有从javascript Node接口继承的方法
- 检查Flash对象是否有来自JavaScript的方法
- 是否有一个JavaScript库或方法可以将一个大小的数组映射到一个新大小的数组
- 有没有javascript方法可以在字符串数组中查找子字符串
- 是否有任何 JavaScript 库实现了瑞典语等字母表的排序方法
- 是否有替代javascript的方法来访问DOM API ?