Funktion foo näkyvyysalue (scope) on globaali niin kuin kuuluukin. Sama funktio nimellä bar on kuitenkin paikallinen:
var foo = function bar() {
if (foo === bar) { return "YES"; }
return "NO";
};
foo(); // funktio toimii
bar(); // funktio ei näy tänne (”ReferenceError: bar is not defined”)Mistä tämä johtuu, ts. mikä on sääntö, jonka mukaan näin kuuluu käydä?
Sääntö löytyy ECMAScriptin määrittelystä.
http://www.ecma-international.org/ecma-262/5.1/#sec-13:
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
Aihe on jo aika vanha, joten et voi enää vastata siihen.