Search code examples
javascriptecmascript-5

Is it legal javascript (ECMAScript) for a function to reference its attributes?


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?


Solution

  • 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:

    let foo = {
      bar: 1,
      baz: foo.bar + 1
    };
    

    fails because the object has not been assigned to foo yet, so foo.bar is undefined.

    With functions this is not a problem, since foo is a reference to the function and bar would not be accessed until the function is invoked:

    function foo() {
      return foo.bar + 1;
    }
    
    foo.bar = 1;