JavaScript模块模式,将修改后的私有变量作为公共变量获取

huangapple go评论59阅读模式
英文:

Javascript Module Pattern, get modified private variable as public

问题

Sure, here's the translated code part:

你能告诉我如何将修改后的私有变量变为公共的吗

let Module = (function(){
  let privateObject = {};

  function init(){
    privateObject = {test:true}
  }

  return {
    init,
    privateObject
  }
})();

Module.init();
console.log(Module.privateObject);
我尝试过类似这样的方法但我相当确定我漏掉了某些东西

let Module = (function(){
  
  function init(){
    publicObject.privateObject.test = true;
  }

  let publicObject = {
    privateObject: {},
    init
  }

  return publicObject;
})();

Module.init();
console.log(Module.privateObject); // 输出 {test: true}

注意:这里的翻译只包括代码部分,不包括问题或其他内容。

英文:

Can you tell me how to get modified private variable as public?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let Module = (function(){
  let privateObject = {};

  function init(){
    privateObject = {test:true}
  }

  return {
    init,
    privateObject
  }
})();

Module.init();
console.log(Module.privateObject);

<!-- end snippet -->

I've tried something like this but I am pretty sure that I'm missing something.

let Module = (function(){
  
  function init(){
    publicObject.privateObject.test = true;
  }

  let publicObject = {
    privateObject: {},
    init
  }

  return publicObject;
})();

Module.init();
console.log(Module.privateObject); // gives {test: true}

答案1

得分: 1

谢谢您的评论。

我已经理解了为什么在赋新值之后
privateObject = {test:true}

Module.privateObject返回了一个空对象,因为Module.privateObject保留了对privateObject先前值的引用。感谢@jabaa

作为问题的解决方案,以下代码完美运行

let Module = (function(){
  let privateObject = {};

  function init(){
    privateObject = {test:true}
  }

  function getPrivate(){
    return privateObject;
  }
  return {
    init,
    getPrivate
  }
})();

Module.init();
console.log(Module.getPrivate());
英文:

Thank you for your comments.

I already understand why with a new assignment of value
privateObject = {test:true}

Module.privateObject returned an empty object because Module.privateObject kept a reference to the previous value of privateObject. Thanks @jabaa

As a solution to the problem for the posterity, the following code works like a charm

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let Module = (function(){
  let privateObject = {};

  function init(){
    privateObject = {test:true}
  }

  function getPrivate(){
    return privateObject;
  }
  return {
    init,
    getPrivate
  }
})();

Module.init();
console.log(Module.getPrivate());

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月19日 22:39:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定