简体   繁体   English

为什么我的模块Javascript代码段在私有变量上返回未定义?

[英]Why does my Javascript snippet for a module return undefined on a private variable?

I am struggling to see why my JS snippet is returning undefined in the console window... 我正在努力查看为什么我的JS代码段在控制台窗口中返回未定义...

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! 因为直接设置myModule.myVal实际上有效!

  return {
    myVal : _myVal,
    setMyVal : _setMyVal
  };

You are returning the current value of _myVal rather than a reference to it (which is what you want). 您将返回_myVal的当前值,而不是对其的引用(这是您想要的)。 After reassigning the variable _myVal in your function, myModule.myVal is still pointing to the old value. 在函数中重新分配变量_myVal之后, myModule.myVal仍指向旧值。

If you want to return a reference, you can use a getter to return it: 如果要返回引用,则可以使用getter来返回它:

  return {
    get myVal() {return _myVal},
    setMyVal : _setMyVal
  };

That is just how JavaScript handles variables and object properties. 这就是JavaScript处理变量和对象属性的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM