JavaScript Encapsulation / JQuery
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 usin开发者_高级运维g 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.
Usually, it is achieved like this:
(function(){
var myLocal = "I'm local!";
window.myGlobal = "I'm global!";
})();
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';
精彩评论