0

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')
};
6
  • 2
    That's not "application" scope. That's just namespaced to an object. There is no "application" scope with vanilla JS. Commented May 8, 2013 at 21:06
  • There shouldn't be any major performance differences, however not defining stuff on the window will make your code less prone to errors due to non-related or poorly written code. Commented May 8, 2013 at 21:09
  • @KevinB so you say its mainly about minimizing human error rather than it being more performant? Commented May 8, 2013 at 21:10
  • 2
    Yes, most patterns in javascript are more for preventing human error and making it easier for humans to read/modify than for performance. Look at jQuery for example (even though it isn't a pattern). jQuery is far less performant than native javascript, however it makes it far easier for us humans to read/write/modify it. Commented May 8, 2013 at 21:12
  • @MattBall thanks for the correction, so given what KevinB said, I guess this is micro-optimization and something to not worry about if we are dealing with a small codebase? Commented May 8, 2013 at 21:14

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

3 Comments

-@Michael so basically what KevinB said in the comments above about "application" scope being less prone to human error?
Preventing name collision is also important. It's common to load several third-party libraries and widgets on a complex page, this pattern minimizes the potential name conflicts.
@timpeterson, Barmar: I agree with both comments. They are both byproducts of structuring the code in modules. The benefits of organising the code in modules are too many to be answered in a StackOverflow post.

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.