[Javascript] Help with closures

Nick Fitzsimons nick at nickfitz.co.uk
Fri Jan 12 16:16:20 CST 2007


On 12 Jan 2007, at 21:29:25, Bill Moseley wrote:

> On Fri, Jan 12, 2007 at 08:00:15PM +0000, Nick Fitzsimons wrote:
>> function testWithBlock() {
>>    var bar = 1;
>>    for (var i = 0; i < 10; i++) {
>>       var bar = i; // this is just redefining the outer bar, not  
>> a  new bar with block scope
>>    }
>>    alert(bar); // shows "9"
>> }
>
> So is this exactly the same then (note lack of var on inner bar)?:
>
>     function testWithBlock() {
>        var bar = 1;
>        for (var i = 0; i < 10; i++) {
>           bar = i;
>        }
>        alert(bar); // shows "9"
>     }
>
> Kind of disturbing, if so. ;)
>

Yes, it's the same. To be precise, "var declares a variable,  
optionally initialising it to a value." So you could write

     function testWithBlock() {
        var bar;
        for (var i = 0; i < 10; i++) {
           bar = i;
        }
        alert(bar); // shows "9"
     }

although I'm not sure if you find that any less disturbing ;-)

>> I would suggest having a look at ECMA 262, which
>> defines the ECMAScript language of which JavaScript is an
>> implementation, but nobody who's read it all the way through (several
>> times) would willingly inflict it on another human being :-)
>
> I'd like to, but I'm enjoying poking hot sticks in my eyes too much.

:-)

A good source of information is on Mozilla's site:
<http://developer.mozilla.org/en/docs/JavaScript>

The Core reference is good for looking stuff up quickly, and the  
Language Guide will help you get your head round oddities like  
function scope.

>> HTH,
>
> It does.  Thanks much.
>

No problem. Now, it's Friday night and the pub's open. Have a good  
weekend :-)

Cheers,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list