Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know JavaScript Function Expression vs Function Declaration, but what is this? Named Function Expression? [duplicate]

Tags:

javascript

oop

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:

  1. What happens to abc? Why it works? abc can be called but not def, why?
  2. Is it a function declaration or an expression?
  3. def is undefined - why? If it is supposed to be, are there memory leaks?
  4. Why is abc.prototype is function def?

Thanks

like image 293
Om Shankar Avatar asked Sep 05 '25 01:09

Om Shankar


2 Answers

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".

like image 69
Bergi Avatar answered Sep 06 '25 14:09

Bergi


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.

like image 42
KooiInc Avatar answered Sep 06 '25 14:09

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!