我正在尝试创建模仿 jQuery 设计模式的自定义工具箱。基本上,这个想法有点源自这篇文章:jQuery plugin design pattern (common practice?) for dealing with private functions (检查“大卫”给出的答案)。
所以这是我的工具箱函数:
(function(window){
var mySpace=function(){
return new PrivateSpace();
}
var PrivateSpace=function(){
var testCache={};
};
PrivateSpace.prototype={
init:function(){
console.log('init this:', this);
return this;
},
ajax:function(){
console.log('make ajax calls here');
return this;
},
cache:function(key,selector){
console.log('cache selectors here');
testCache[key]=selector;
console.log('cached selector: ',testCache);
return this;
}
}
window.hmis=window.m$=mySpace();
})(window)
现在,如果我像这样执行这个函数:
console.log(m$.cache('firstname','#FirstNameTextbox'));
我收到错误“testCache”未定义。我无法访问原型(prototype)缓存函数中的变量“testCache”。我应该如何访问它?基本上,我想做的是,我想将我所有的 jQuery 选择器缓存到一个对象中,并在将来使用这个对象。
最佳答案
testCache 隐藏在 new PrivateSpace
创建的闭包中。
此处使用的正确模式是
var PrivateSpace=function(){
this.testCache={};
};
PrivateSpace.prototype={
cache:function(key,selector){
this.testCache[key]=selector;
return this;
}
}
这里的本质部分是this
。
但是整段代码看起来有点做作——当只创建一个实例时,没有理由使用原型(prototype)模式。您应该改为依赖可通过共享范围(闭包)访问的变量。
(function(window)(
var cache = {}, mylib;
window.mylib = mylib = {
cache: function(key, selector) {
cache[key] = selector;
return mylib;
}
}
})(window);
更新
顺便说一句,如果没有真正的理由,请不要遵循 jQuery 模式 ;)
更新
隐私空间的更好方法可能是
function PrivateSpace(){
var cache = {};
return {
cache: {
get: function(key){
return cache[key];
},
set: function(key, value) {
cache[key] = value;
}
},
init: function() {
...
}
};
}
这是通常用于提供私有(private) 成员的模式..
关于javascript - 在 jQuery 中访问私有(private)变量的问题,如可链接设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2840258/