سؤال

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