zrooda
zrooda

Reputation: 3673

Prototype difference between function declaration and expression

var foo = function(){alert('foo')}
function bar(){alert('bar')}

Why does foo.prototype point to Object, but the named function bar.prototype points to itself?

I should add that this behavior is observed from browser console.

Upvotes: 1

Views: 642

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

If you're using a console such a Chrome to log the value of a prototype object then I suggest you don't. The Chrome console, like other browser consoles, formats the output of the prototype object.

So for a named function it will log the name of the function, but for an unnamed function it will simply log Object. This does not mean that the prototype of the function points to Object or the function itself. It's just that that's what the console is showing you (someone should sue them for that). See for yourself: http://jsfiddle.net/2xkpC/

How does it know the name of a function from it's prototype? Well, the prototype of a function has a property called constructor which points back to the function itself, and the name of the function is stored as a string in a property called name on the function. So if you log a prototype object then it will display prototype.constructor.name || "Object":

var foo = function(){alert('foo')}
console.log(foo.prototype); // logs "Object"

function bar(){alert('bar')}
console.log(bar.prototype); // logs bar.prototype.constructor.name

See the demo here: http://jsfiddle.net/4bWfn/

If you open your console and click that triangle near the logged output then you'll see the constructor and the __proto__ properties of the prototype object. Under constructor you'll also see the name property.

To know more about inheritance in JavaScript and the prototype object read this answer: https://stackoverflow.com/a/8096017/783743

Upvotes: 5

zb'
zb'

Reputation: 8059

Because var foo in your example it is pointer to anonymous function.

compare to

var foo = function me(){alert('foo');}
test=foo;
console.log(test.prototype);

here var foo is pointer to named function.

Upvotes: -1

Related Questions