Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, do not forget the <code>var</code> keyword when declaring variables. When you declare <code>value = 42</code> inside <code>myFunc</code>, you are actually creating a variable in the global namespace instead of the function scope. It should start like this:</p> <pre><code>function myFunc() { var value = 42; </code></pre> <p>Now, <code>myObject.result</code> is returning 42 because <code>myFunc</code> returns your <code>result</code> object which contains a copy of the <code>value</code> variable declared inside the function.</p> <p>Your functions <code>setValue</code>, <code>getValue</code> and <code>incrementValue</code> are changing the value of <code>value</code>, not <code>result.value</code>. When you call <code>myObject.value</code>, you are getting the value from the returned object, not the inner variable of your function.</p> <p>You could get it to work using something like this:</p> <pre><code>function myFunc() { var value = 42; var result = { value: value, getValue: getValue, incrementValue: incrementValue, setValue: setValue }; return result; function setValue(y) { result.value = y; } function getValue() { return result.value; } function incrementValue() { result.value++; } } </code></pre> <p>However, there are better design patterns than this. You could use the <code>new</code> keyword and <code>prototype</code> to define the methods available for the objects returned from your function. Take this example:</p> <pre><code>function myFunc() { this.value = 42; } myFunc.prototype.setValue = function(y) { this.value = y; } myFunc.prototype.getValue = function(y) { return this.value; } myFunc.prototype.incrementValue = function(y) { this.value++; } var myObject = new myFunc(); console.log(myObject.getValue()); // 42 myObject.setValue(30); myObject.incrementValue(); console.log(myObject.getValue()); // 31 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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