Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

a basic explanation is that by preceding a variable declaration with var creates a property on the nearest containing function

This is not true, the var hoist the variable and scopes it to the function, but does not create it as a property of the function. A function is defined in its outer function scope, an it's properties will persist across calls.

  function foo() {
    var bar = 1;
    foo.baz = 2;
  }

  foo();

  foo.bar; // is undefined
  foo.baz; // is 2
Adding properties to functions is useful for memoization, but is different than what the var statement does.

Your summary of that section is a better explanation:

all variables are scoped to a function (which is itself an object), and where you declare those variables with var determines the function they are scoped to.

You might add, if you never declare the variable with var it is implicitly declared global.



thanks for the help




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: