Problem with access to private variables in jQuery, for example, with a solid design scheme

I am trying to create my own toolbox that mimics a jQuery design template. In principle, this idea follows somewhat from this publication: jQuery plugin design template (common practice?) To work with private functions (check the answer given by "David").

So here is my toolbar function:

(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)

Now, if I perform this function, for example:

  console.log(m$.cache('firstname','#FirstNameTextbox'));

I get the error "testCache" is not defined. I cannot access the variable "testCache" in my prototype cache function. How do I access it? Basically, I want to do this, I want to cache all my jQuery selectors in an object and use this object in the future.

+3
2

testCache , new PrivateSpace.

var PrivateSpace=function(){
    this.testCache={};
};   

PrivateSpace.prototype={
    cache:function(key,selector){
        this.testCache[key]=selector;
        return this;
    }
}

this.

- , . , ().

(function(window)(
     var cache = {}, mylib;

     window.mylib = mylib =  {
          cache: function(key, selector) {
              cache[key] = selector;
              return mylib;
          }
     }

})(window);


, , jQuery, ;)


PrivateSpace

function PrivateSpace(){
    var cache = {};
    return {
        cache: {
            get: function(key){
                return cache[key];
            },
            set: function(key, value) {
                cache[key] = value;
            }
         },
         init: function() {
             ...
         }
     };
 }

, .

+5

.

, PrivateSpace ( .

+1

Source: https://habr.com/ru/post/1745569/


All Articles