3

<html><body><button>setSpeed</button>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>

$(document).ready(function(){
  $('button').on('click', function(){
    _.setSpeed();
    console.log('_.slow: ' + _.slow);
  });
});

var _ = (function(){
  var slow = 4;
  
  function setSpeed(){ 
    if (slow == 4) {
      slow = 1;
    } else if (slow == 1){
      slow = 16;
    } else {
      slow = 4;
    }
    console.log('slow: '+ slow);
  }
  return { slow: slow, setSpeed: setSpeed };

})();

</script></body></html>

I don't understand why the console.log for slow and _.slow don't match? What am I missing?

By returning both the var slow and function setSpeed in the IIEF, I would think they should match.

shirha
  • 453
  • 3
  • 11

1 Answers1

1

When you do this:

return { slow: slow, setSpeed: setSpeed };

You are creating a new object with two properties, slow and setSpeed. The value for slow is assigned from the var slow. Since that is a primitive type (not a reference value) you're getting a copy of the current value of slow (4).

When you call setSpeed, it modifies the var slow changing it to 1. This does not affect _.slow (since it's not a reference).

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38
  • You can try to add a getter function for slow if you want to check the value of slow inside yout IIEF. `function getSlow(){ return slow; }` in your `return` part `return { getSlow: getSlow, setSpeed: setSpeed };` or you can bind a getter function for your `slow` property. (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/get) – leonard.javiniar Oct 27 '16 at 05:56