Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
I am aware of the differences between Function Declarations and Expressions, but have come across this code involving function name and want to understand what happens when we run it:
var abc = function def() {
console.log("Wait! What??");
}
I know that this is not a way to JavaScript, but just want to know few things:
abc
? Why it works? abc
can be called but not def
, why?def
is undefined
- why? If it is supposed to be, are there
memory leaks?abc.prototype
is function def
?Thanks
What happens to abc?
It contains a function object. If you are doing nothing with it, it will be garbage-collected.
Why it works?
Why not? What "works"?
abc can be called but not def, why?
This is only true from outside, and not in IE. See below.
Is it a function declaration or an expression?
It is a function expression. You can easily see that as it is part of an assignment expression; declarations always need to be on top level (of functions or global code)
def is undefined - why?
Only from outside. A function expression does not create variables. "def" is the name of the function, and inside the function it is a reference to the function as well. This allows recursion for example without using any outer variables.
var abc = function def() {
def === abc; // true
def.name; // "def"
}
abc();
def; // undefined
If it is supposed to be, are there memory leaks?
Yes, in Internet Explorer. It creates two distinct functions from that code. For the details, see http://kangax.github.com/nfe/#jscript-bugs
Why is abc.prototype is function def?
It is not. It is just an object. Maybe it is shown with that name in your console, as belongs to a function named "def".
It's a named function expression. A possible use for this could be:
var abc = function def() {
def.test = 'Wait!'; //< sort of a static property
console.log(def.test+" What??");
}
But beware.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With