2

I am struggling to see why my JS snippet is returning undefined in the console window...

var myModule = (function(){

  var _myVal;

  function _setMyVal(arg){

    _myVal = arg;

  }


  return {
    myVal : _myVal,
    setMyVal : _setMyVal
  };


}());

myModule.setMyVal("ss");

console.log(myModule.myVal);

Because setting myModule.myVal directly actually works!

1
  • myModule is an IIFE which has already been invoked, setting myVal to undefined Commented Nov 17, 2014 at 10:44

2 Answers 2

4
  return {
    myVal : _myVal,
    setMyVal : _setMyVal
  };

You are returning the current value of _myVal rather than a reference to it (which is what you want). After reassigning the variable _myVal in your function, myModule.myVal is still pointing to the old value.

If you want to return a reference, you can use a getter to return it:

  return {
    get myVal() {return _myVal},
    setMyVal : _setMyVal
  };
Sign up to request clarification or add additional context in comments.

1 Comment

The answer is good although I'm not keen on the 'get' keyword I haven't seen it a lot and worry it will confuse people. I have refactored to two methods as it seems more orthogonal.... The getter buries the 'get' inside the inner function. getReferences : _getReferences, setReferences : _setReferences
0

That is just how JavaScript handles variables and object properties.

var x = 2;
var y = {x: x};   // at this point, y.x is set to the number two,
                  // it bears no reference to the variable x

console.log(x, y.x); // 2 2

x = 3

console.log(x, y.x); // 3 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.