On Wed, Mar 16, 2011 at 4:05 PM, shaun <[email protected]> wrote:
>
>
> I think i read in the Google Javascript style guide that for situations
> like the one above, functions should be declared like:
>
> var f = function...
>
> I guess this is so var hoisting does the "right thing" for you?
>

No. I actually didn't mention this because the two aren't _exactly_ the
same. The difference is in fact about hoisting (but only that).

Hoisting is the effect that variables and function declarations in a script
or inside a function are "created" before the script or function is actually
executed.

For variables, this means that the variable is created (but NOT the initial
assignment!). So at the start of any function, all variables declared at any
point inside that function can already be used before their declaration. Not
adviced (it causes confusion), but possible nevertheless. Classic example:

function(){
log(x); // undefined
var x = 5;
}

For function declarations (not expressions!) the above description applies
as well except that the function is also created and assigned (But not
executed! But since you can't really immediately execute a function
declaration, this confusion is less likely to happen). The classic example
goes:

log(f); // outputs whatever the browser makes of functions (but not
"undefined" as above)
function f(){};

Having said all that.. I virtually always prefer to use function expressions
and not rely on hoisting. Some people do prefer to use hoisting so they can
put the "meat" of the code on top. Of course, when using proper inheritance
and all that, hoisting functions is hardly ever an issue anymore :)

When you want to create functions depending on some factor (so inside an
if), as far as the specification goes, you can only use function expressions
(var f = function ...).

So, recap:

function f(){}  // var f is hoisted and will contain the function

var f = function(){}; // var f is hoisted but the function value is NOT
var f = function g(){}; // var f is hoisted but the function value is NOT.
var g should not be hoisted, or even exist, because it should only exist
inside the function.

Hope this helps... :)

- peter

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to