1
这一个为JavaScript大师:javascript私人变量访问问题
我正在试验一个新的JavaScript框架。它的结构灵感来源于强大的jQuery。
它有一个叫做$j
全局变量,和..哦,只是看到它在行动:
/* file: jfoo.js */
$j = new (function(){
var modules=[];
this.loadModule = function(mod) {
modules[ modules.length ] = mod;
}
this.hasModule = function(mod) {
for(ind in modules)
if(modules[ind]==mod) return true;
return false;
}
})();
你看那个模块是私有变量。没问题;这正是我的意图。
现在,我想编写一个插件,将$j.loadBatch
方法添加到我的系统中。所以..
/* file: loadBatch.jfoo.js */
!$j || (function(){
$j.loadBatch = function(batch) {
for(ind in batch)
modules[ modules.length++ ] = batch[ind];
}
})();
但是,因为这种方法是不是在文件jfoo.js
的关闭工作的一部分,这是不可能的。
我也试过这个版本:
/* file: jfoo.js */
$j = new (function(){
var modules=[];
this.loadModule = function(mod) {
modules[ modules.length ] = mod;
}
this.hasModule = function(mod) {
for(ind in modules)
if(modules[ind]==mod) return true;
return false;
}
this.extend = function(extensions) {
for(ext in extensions)
this[ext] = extensions[ext];
}
})();
和
/* file:loadBatch.jfoo.js */
!$j || (function(){
$j.extend({
loadBatch : function(batch) {
for(ind in batch)
modules[ modules.length++ ] = batch[ind];
}
});
})();
但我没有更好的结果。
所以,问题:
- 有没有办法,我可以写在一个单独的文件中
loadBatch
方法,仍然有其访问私有方法modules
什么办法? (我希望答案是一个响亮的否,但是,谁知道?) - 是否有任何其他方式可以达到预期的效果,而不会使公开
modules
? (我知道如何进行,如果我公开) - jQuery使用私人成员?它如何克服其“私人可访问性”问题呢?
感谢,
JRH
任何想法如何jQuery做到这一点? jQuery实际上做到了吗? – jrharshath 2009-06-25 14:17:26