OpenSource For You

In this month’s column, the discussion on the features of Javascript continues. For the last couple of months, what has been covered is dynamic languages such as Javascript, and how they differ from traditiona­l statically compiled languages like C/C++. In

-

In last month’s column, we had looked at a Iew examples oI closures. The oIficial Wikipedia entry defines a closure as “…a Iunction together with a reIerencin­g environmen­t Ior the non-local variables oI that Iunction.” Well, while this definition does in Iact cover closures, it Iails to distinguis­h how closures are diIIerent Irom, say, Iunction pointers in C/ C++. AIter all, a Iunction has a reIerencin­g environmen­t Ior globals in C/C++, and can be passed around through a Iunction pointer—so does that constitute a closure? No, not really. Let us consider the example below: var count = 2M; function incrementC­ount(int incr) {

return count + incr; } assert( incrementC­ount(5) == 25);

Here, the Iunction call to incrementC­ount() reIerences the variable count, and hence the returned value is 25. Consider a slight modificati­on oI the above code: var count = 2M; function incrementC­ount(int incr) {

return count + incr; } count = 3M; assert( incrementC­ount(5) == 25);

Now the assert actually Iails, and the return value Irom ‘incrementC­ount ’ is actually 35, not 25. That is because the reIerence to the global variable ‘count ’ returns the current value oI the variable ‘count ’, and not its value Irom the lexical scope reIerence oI ‘count ’ in the Iunction ‘incrementC­ount ’. Hence, the above two examples are not really closures. ThereIore, a slightly improved definition would be that a closure is a function that has the following properties: ,t can be passed around like an object. ,t ‘remembers’ all variables that were in scope when it was created, so that these can be reIerenced by the called closure even though the parent Iunction where the variables were defined is no longer in scope. The second property is the most diIficult thing Ior a C/C++ programmer to understand. The Tuestion that crops up is: How can the closure Iunction access the variables oI the enclosing Iunction when the latter has already returned, and its local variables have gone out oI scope? Well, the answer to that is that JavaScript supports closures as first-class citizens, hence as long as there is a reIerence to the enclosing Iunction’s locals by a closure Iunction, the JavaScript runtime will not Iree up the local variables oI the enclosing Iunction. Hence, these variables remain accessible to the closure Iunction, even though the execution oI the enclosing Iunction has completed.

Closures need to be supported as a Ieature oI the language. Languages such as L,SP, Scheme

Newspapers in English

Newspapers from India