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