views:

226

answers:

2

I am trying to figure out how to keep my page variables in my application from being defined globally. I've come up with a few methods but am wondering if there is a general standard approach people use.

I've got my plugin design pattern down using this approach: http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html. But I'm just not sure how to handle my page level encapsulation.

+3  A: 

Usually, it is achieved like this:

(function(){

    var myLocal = "I'm local!";

    window.myGlobal = "I'm global!";

})();
Vincent
When I know that jQuery is around, I usually pollute the `$` namespace instead of `window`. `$.myCompany` becomes the hook point, everything else gets wrapped in a function enclosure.
gnarf
+1 This is, in fact, the approach jQuery itself uses for the same purpose. The entire contents of jquery.js are wrapped like so: `(function(window, undefined) { ... })(window);` Although I don't really understand the need to pass `window` into the function. Even if `window` wasn't passed, I thought it would still be available from within the container function.
Mike M. Lin
A: 

Vincent's got the most watertight approach (wrap everything in a function).

The other thing people do is to define a global object that more or less works as a namespace for your package.

window.ChrisPkg = { global1: ['a','b','c'], global2: 42 globalfunc: function () { alert('hello world!'); } }

ChrisPkg.extraGlobal = 'foo';

Weston C