Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript closures - lifetime of variables
    text
    copied!<p>Being fairly new to Javascript and from a c# background I have been stumbling along adequately. I knew that soon enough I would need to get my head round the fact that functions are objects in their own right and that JS closures are often the cause of confusion. </p> <p>I am trying to understand this little snippet of code</p> <pre><code>// Function which returns object with function properties function myFunc() { value = 42; var result = { value: value, getValue: getValue, incrementValue: incrementValue, setValue: setValue, }; return result; function setValue(y) { value = y; }; function getValue() { return value; }; function incrementValue() { value++; }; }; // Helper function to print out results function printResults(m,x){ $('#output').append(m + ': ' + x).append('&lt;br/&gt;'); }; var myObject = myFunc(); // returns the object printResults('Inital call to getValue',myObject.getValue()); myObject.setValue(59); printResults('Called changeValue',myObject.getValue()); printResults('Value property of object',myObject.value); printResults('Called getValue again',myObject.getValue()); myObject.incrementValue(); printResults('Call increment value',myObject.getValue()); printResults('Value property of object',myObject.value); </code></pre> <p>I get the following results when run in jsFiddle</p> <pre><code>Inital call to getValue: 42 Called changeValue: 59 Value property of object: 42 Called getValue again: 59 Call increment value: 60 Value property of object: 42 </code></pre> <p>These show that the functions are using the variable <code>value</code> within their closure and this persists between invocation of the inner functions. BUT, the value of <code>value</code> does not change in the returned object.</p> <p>I think I get the basic point that functions are executed using the scope chain that was in effect when they were defined. </p> <p><strong>Questions</strong> Can I make the <code>value</code> property of the returned object operate in the same way - or is the only way to return it via a function, since the latter retains the variable in its closure?</p> <p><strong>And</strong>, just for confirmation, for every invocation of <code>myFunc()</code>, I assume I will get an object whose function properties will have their own scope chain and therefore independent of each invocation.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload