-7

I have a little bit of experience in JavaScript but JavaScript Closure makes me confused.

Jim G.
  • 15,141
  • 22
  • 103
  • 166
linlin
  • 15
  • 8

1 Answers1

2

To understand what the closure is going to do, you need to understand the scope of local variables.

In Java, you can declare a new, distinct local variable in any {} block.

In Javascript, there is different behavior. The interpreter allows declaring a local variable anywhere, but these variables will only be distinct if they are in different functions.

There is no loop scope or loop-defined variables in Javascript, so for(x=0;x<10;x++){ var j=... behaves exactly like var j; for(x=0; x<10; x++){ j = ..

This is why in Javascript one often wraps one function in another function in order to create a well behaved scope.

Paul
  • 26,170
  • 12
  • 85
  • 119
  • you means like write the function in jquery or Is it smiliar jquery, javascript closure and Ajax? – linlin Apr 01 '11 at 19:08
  • Thanks Paul. where can I use javascript Closure? Is it useful or not – linlin Apr 01 '11 at 19:19
  • 1
    jQuery is a library of prewritten JavaScript. A closure is a language construct. Ajax is the technique of using JS to communicate with a webserver. You are comparing a motor parts shop to an engine and to driving to the beach. – Quentin Apr 01 '11 at 19:21