Is it legal javascript (ECMAScript-5) for a function to reference its attributes?
var baz = function(callback) {
return callback();
};
var foo = function() {
return foo.bar;
}
foo.bar = 1;
foo(); // 1?
baz(foo); // 1?
Edit: can you refer me to the part of the ECMA specification that declares this is legal?
Yes.
Folks often run into a problem with this when using objects, which are evaluated during initialization and don't exist while attempting to reference their properties. This is not a problem with functions, since the property isn't accessed until the function is invoked later.
For example:
fails because the object has not been assigned to
foo
yet, sofoo.bar
is undefined.With functions this is not a problem, since
foo
is a reference to the function andbar
would not be accessed until the function is invoked: