Wednesday, January 29, 2014

Random JavaScript Tips (1)

After learning JavaScript for 2 days, there are quite a bit of difference between it and Java. One big difference that I am stilling getting used to is the omission of block scope.

In JavaScript, all variable declaration are hoisted to the top of enclosing function or the global script, where as in Java the best practice is to declare variables in the nearest enclosing block. According the creator of JavaScript, Brendon, this design choice is due to short of time when they developed it: a relevant question on StackOverflow.

A more important fact is the implementation of a full Closure in JavaScript. The closure a nested function, together with the reference to local variables of all its outer functions. This is very similar to how Java handle nested classes, where inner class can access the instance variables and methods of (the instance of) it outer class. However, Java don't have a function level closure. For example, the anonymous inner class or local class can only access local variables of enclosing method that are declared final. So this is not real closure.