from javascript.info:

function makeArmy() {

  var shooters = []

  for(var i=0; i<10; i++) {

    var shooter = function shoot() {
      alert( shoot.i )
    }
    shooter.i = i

    shooters.push(shooter)   
  }

  return shooters
}

var army = makeArmy()

army[0]() // 0
army[1]() // 1

The interesting part:

var shooter = function shoot() {
  alert( shoot.i )
}
shooter.i = i

My question is this: why does the following not work:

var shooter = function() {
  alert( shooter.i )
}
shooter.i = i

In other words, why does the first one work as expected, while the second one does not? What is the actual difference between the first (giving the function itself a name and using it from within the function), and the second one (using the variable which references to the function)?

有帮助吗?

解决方案 2

You can't refer to the variable shooter until its initializer expression (function() {...}) has completed. If instead you said

var shooter;
shooter = function() { alert(shooter.i); }

it would work OK because the variable is already declared and in scope at the point where the function expression is evaluated.

其他提示

When a function has a name (a declaration), it is defined at parse time. It becomes global in scope.

Otherwise it is defined at run time.

http://markdaggett.com/blog/2013/02/15/functions-explained/

Just to add on to what Steve said. You'll hear the term "hoisted" when referring to function declarations.

In this example, it doesn't necessarily matter when the function is declared because when your script is parsed it first goes through and looks for all function declarations.

i.e.

alert(fnDeclaration());
function fnDeclaration() {
    return "It works!";
}

In the case when you do a function expression, you can only use the function after it has been assigned because functions are values in JavaScript.

i.e.
alert(fnDeclaration());
var fnDeclaration = function() {
    return "It won't work :(";
}

This is the general gist of the differences between the two.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top