0

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.

2 Answers 2

3

Usually, it is achieved like this:

(function(){

    var myLocal = "I'm local!";

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

})();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
+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.
0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.