Javascript - Do I need to use 'var' when reassigning a variable defined in the function's parameters?

前端 未结 4 1081
情书的邮戳
情书的邮戳 2021-01-18 07:20

I\'ve found many definitions of the \'var\' statement but most of them are incomplete (usually from introductory guides/tutorials). Should I use \'var\' if the variable &

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 07:40

    Nope, the order in which names are defined when entering an execution scope is as follows:

    1. function parameters (with value passed or undefined)
    2. special name arguments (with value of arguments if doesn't exist)
    3. function declarations (with body brought along)
    4. variable declarations (with undefined if doesn't exist)
    5. name of current function (with body brought along, if doesn't exist)

    This means that in this code, foo refers to the function parameter (which could easily be changed):

    function foo(foo) {
      var foo;
      alert(foo);
    }
    foo(1); // 1
    

    If you're using a function declaration inside for foo, that body will override all others. Also, note that this means that you can do this:

    function foo(arguments) {
        alert(arguments);
    }
    foo(); // undefined
    foo(1); // 1
    

    Don't do that.

提交回复
热议问题