質問

Maybe this is a stupid question but I couldn't find an answer on it. Assume we have code like this:

function makeFunc() {
  var name = 'Billy';
  var unusedVariable = 'unused';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();

As far as I understand, in this example a variable name will be collected when there won't be references on it, so it will live while the closure myFunc lives. But will unusedVariable live while myFunc lives? In other words, does displayName() 'captures' this unusedVariable even if it is unused?

役に立ちましたか?

解決

yes. All the variables created in "makeFunc" scope will exist in the closure, irrespective of whether used or not. To be precise, that is what closure means. Inside "displayName", you 'can' (not "must') refer to both those variables.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top