shirha shirha - 1 month ago 8
Javascript Question

revealing module pattern inner outer variable mismatch



<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.

Answer

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).