shirha shirha - 1 year ago 80
Javascript Question

revealing module pattern inner outer variable mismatch

<script src=""></script>

$('button').on('click', function(){
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 };



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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download