2

I'm assigning a named function expression to a property of an object:

var foo = {};

foo.bar = function bar(){
    console.log('bar');
};
  • foo.bar() => bar
  • bar() => ReferenceError: bar is not defined

Why can't I call bar() directly, why isn't it defined?

I know that I can simply chain the assignment like var bar = foo.bar = function(){}, so I'm not looking for a work-around or other solution, I'm only interested in why it doesn't work.

I've tested in Chrome console and Node.JS.

Drahcir
  • 11,772
  • 24
  • 86
  • 128
  • 1
    `bar()` actually means `window.bar()` which is not defined within `window` namespace. Instead it is defined in `foo` namespace. – Rahil Wazir May 27 '14 at 16:41
  • See also [Javascript: Inconsistency when assigning a named function to a variable (named function expression)](http://stackoverflow.com/questions/14732107/javascript-inconsistency-when-assigning-a-named-function-to-a-variable-named-f) – p.s.w.g May 27 '14 at 16:42

1 Answers1

2

Named function expressions are simply not supposed to work that way. The function name is only visible inside the function, not outside.

A function instantiation expression that happens to have a name is not the same thing as a function declaration statement. Those are two distinct syntactic (and semantic) entities in the language.

Pointy
  • 405,095
  • 59
  • 585
  • 614