Tutorial :JavaScript Encapsulation / JQuery



Question:

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.


Solution:1

Usually, it is achieved like this:

(function(){        var myLocal = "I'm local!";        window.myGlobal = "I'm global!";    })();  


Solution:2

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »