I'm trying to create my custom toolbox which imitates jQuery's design pattern. Basically, the idea is somewhat derived from this post: jQuery plugin design pattern (common practice?) for dealing with private functions (Check the answer given by "David").
So here is my toolbox function:
(function(window){
var mySpace=function(){
return new PrivateSpace();
}
var PrivateSpace=function(){
var testCache={};
};
PrivateSpace.prototype={
init:function(){
co开发者_JS百科nsole.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)
Now, if I execute this function like:
console.log(m$.cache('firstname','#FirstNameTextbox'));
I get an error 'testCache' is not defined. I'm not able to access the variable "testCache" inside my cache function of the prototype. How should I access it? Basically, what I want to do is, I want to cache all my jQuery selectors into an object and use this object in the future.
testCache is hidden in the closure that new PrivateSpace
creates.
The correct pattern to use here is
var PrivateSpace=function(){
this.testCache={};
};
PrivateSpace.prototype={
cache:function(key,selector){
this.testCache[key]=selector;
return this;
}
}
The essential part here is this
.
But the entire piece of code seems a bit contrived - there is no reason to use a prototype pattern when only a single instance is to be created. You should instead rely on variables accessible through a shared scope (closure).
(function(window)(
var cache = {}, mylib;
window.mylib = mylib = {
cache: function(key, selector) {
cache[key] = selector;
return mylib;
}
}
})(window);
Update
And by the way, do not follow the jQuery pattern without having a real reason to do so ;)
Update
A better approach for PrivateSpace could be
function PrivateSpace(){
var cache = {};
return {
cache: {
get: function(key){
return cache[key];
},
set: function(key, value) {
cache[key] = value;
}
},
init: function() {
...
}
};
}
This is the pattern normally used for providing private members..
The prototype pattern does not allow per-instance private variables.
You can either use a private cache that will be accessed by all instances of PrivateSpace (by declaring the cache inside your outer most closure, or stop using the prototype pattern.
精彩评论