Friday, February 25, 2011

Resig's Learn Javascript

Learning via John Resig's tutorials on advanced Javascript.- http://ejohn.org/apps/learn/

The tutorials are very informative but they seemed confusing to me so I started taking notes based on what I understood.

Please correct me if I am wrong.

Observations/Conclusions from Chapter 2 i.e. pages 1 to 16:

1. Definition of Named function:
function <function name> (){//func body here}

2. Definition of Anonymous function:
var funcAlias = function (){//func body here} OR
var funcAlias = function
<function name> (){//func body here} (this is weird but true)

3. Anonymous funcs have to be declared *before* being called to be accessable/available - named functions can be named anywhere, even in non-reachable function loops e.g. after return statement

4. Anonymous functions can be named - this is useful when:
    . we create a new object (samurai) and reference the original's method (var samurai = {yell:ninja.yell}) and
    . we redefine the original (ninja = {})
 

     So we can still access named anonymous functions even after their original parent object is redefined - if the parent is redefined, then we cannot access any *unnamed* anonymous functions, only named anonymous functions. This statement can describe the following cases:

. What happens with anonymous functions if their parent object is redefined
. Anonymous named functions can be defined as in 2
. Anonymous named functions can only be accessed within scope of their block
. If a named function has an alias associated with it, it becomes an anonymous function

5. We can avoid naming anonymous functions - If there is a situation where there is a possibility of an object A referencing another object B's methods AND object B may be redefined later,
then use arguments.callee

var ninja = {
yell: function(n){
return n > 0 ? arguments.callee(n-1) + "a" : "hiy";
}
};
assert( ninja.yell(4) == "hiyaaaa",
"arguments.callee is the function itself." );