Based on my experience and the information in Why use named function expressions? and kangax.github.io: Named function expressions, it is clear why the two examples below result in the given output:
Example 1:
var f = function foo() {
console.log(foo);
}
console.log( typeof foo === "undefined" ); // true
console.log( typeof f !== "undefined" ); // true
console.log( f.name ); // foo
Example 2:
var obj = {
fooA: function foo() {
console.log('fooA -> ' + foo.toString());
},
fooB: function foo() {
console.log('fooB -> ' + foo.toString());
}
}
obj.fooA(); // the source of fooA
obj.fooB(); // the source of fooB
console.log(typeof foo === "undefined"); // true
But I'm try to figure out why the identifier is not available to the enclosing scope in the following example:
var obj = {
foo() {
console.log(typeof foo === "undefined"); // true
}
}
obj.foo();
console.log(obj.foo.name); // foo
I guess it is defined somewhere, but information about this seems to be spread over the whole specs. The only clear statement I found was on MDN: Method definitions:
Note : The shorthand syntax uses named function instead of anonymous functions (as in …foo: function() {}…). Named functions can be called from the function body (this is impossible for anonymous function as there is no identifier to refer to). For more details, see function.
But in my option this contradicts the observation, because it says this kind of function is a named function, and therefore it should be accessible from the function body.
The function has a name, because obj.foo.name
is foo
, but foo
is not accessible from inside of itself.
Is the observed behaviour correct with regard to the specs, and where is this defined in the specs?