views:

259

answers:

1

Hi,

this one for the javascript gurus:

I'm experimenting with a new javascript framework. Its structure is inspired by none other than the mighty jQuery.

It has a global variable called $j, and .. oh, just see it in action:

/* 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;
    }
})();

You see that modules is a private variable. No problem; that just what I intended.

Now, I want to write a plugin that adds a $j.loadBatch method to my system. So..

/* file: loadBatch.jfoo.js */
!$j || (function(){
    $j.loadBatch = function(batch) {
         for(ind in batch)
             modules[ modules.length++ ] = batch[ind];
     }
})();

But, since this method is not part of the closure in file jfoo.js, this is not possible.

I also tried this version:

/* 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];
    }
})();

and

/* file:loadBatch.jfoo.js */
!$j || (function(){
    $j.extend( {
     loadBatch : function(batch) {
      for(ind in batch)
       modules[ modules.length++ ] = batch[ind];
     }
    });
})();

But I got no better results.

So, the questions:

  • Is there any way that I can write the loadBatch method in a separate file and still have it access the private method modules? (I expect the answer to be a resounding NO, but, who knows?)
  • is there any other way by which I can achive the desired effect without making modules public? (I know how to proceed if I make it public)
  • does jQuery use private members? how does it get over its "private accessibility" problems then?

Thanks,

jrh

+3  A: 

AFAIK there's no way to give access to a "private" variable (variable only within the scope of a closure) to some execution contexts outside its scope, but not others. (e.g. you could write an accessor method but couldn't limit who gets access)

Jason S
any idea how jQuery does it? Does jQuery actually do it?
Here Be Wolves
jQuery uses a build step to glue all the files together into one before sending to the client.
Mark Story