-4

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

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

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

  return {
    init,
    privateObject
  }
})();

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

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}
Tom
  • 151
  • 6
  • 2
    I made your code runnable and it does not give an empty object... – Ruan Mendes Apr 19 '23 at 14:44
  • can you check again? Ive change privateObject = {test:true} – Tom Apr 19 '23 at 14:53
  • JavaScript is a language that has object reference as variables. `Module.private` contains a copy of the reference. `privateObject = {test:true}` assigns a new, different reference. – jabaa Apr 19 '23 at 15:33
  • As a solution you can either modify the object (`privateObject.test = true;`) or use a getter function – jabaa Apr 19 '23 at 16:22

1 Answers1

1

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

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

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

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

Module.init();
console.log(Module.getPrivate());
Tom
  • 151
  • 6