tim peterson
tim peterson

Reputation: 24315

window vs. application scope for Javascript variables

Can someone explain reasons for putting all variables with application scope vs. window scope? Is application scope ALWAYS better?

  1. performance?
  2. prevent naming collisons?
  3. other reasons?

window scope

var myFunction1=function(){
   //do something
};

var myFunction2=function(){
   //do something else
};

var myObject1={
   //store stuff
};

var myDOMElement1=$('.myDOMElement1');

application scope

var myApplication={
   'myFunction1':function(){
      //do something
   },
   'myFunction2':function(){
      //do something else
   },
    'myObject1':{
      //store stuff
   },
    'myDOMElement1':$('.myDOMElement1')
};

Upvotes: 0

Views: 605

Answers (1)

Michael
Michael

Reputation: 83

The reason is information hiding and encapsulation. Since JavaScript does not have built-in the notion of Modules (or Components or Classes), in order to organize your code, you must employ a pattern similar to the one you show in "Application Scope".

For a more thorough explanation search the Internet for the "JavaScript Module Pattern".

Upvotes: 2

Related Questions