This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can somebody tell me the code difference?

 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the first one works but the second one doesn't work? What does it make a difference with a "var" in the front?
first one that works:



second one that doesn't work:
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64631
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm assuming the use of jQuery? (It's a good idea to let us know that up front.)

I'm not even sure what you are trying to do here? Why do you have a declaration passed to the jQuery function in the first place? It'll work to establish the function as a ready handler, but it's really really odd.

What is your actual intention?

And to answer the specific question: var is used within non-global scopes to limit the scope of a variable to the current function. Without var, implicitly declared variables will become part of the global scope.
 
Colin Zheng
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply, Mr. Bibeault.
Yes, I forgot to mention the use of jQuery.
I am learning Javascript and know that an anonymous function is expected to the the ready handler. I am just curious what it will do if I declare it with a name.
So, the global scope declared function works as a ready handler but a non-global scope declared one doesn't. Can you tell me why? Maybe I can better understand how JavaScript works from finding the answer.

Thanks,
Colin
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64631
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Colin Zheng wrote:So, the global scope declared function works as a ready handler but a non-global scope declared one doesn't.

It has nothing at all to do with scope.

The problem is that you're trying to use var as a function parameter. No can do.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic