javascriptrevealing-module-pattern

JavaScript Revealing Module pattern private variable state


I have recently started working on a JavaScript project and coming from Java world things seem, not surprisingly, weird at times.

I was implementing a simple module (Using revealing module pattern, afaik) which would provide config based on initialisation but notice that after a "local" variable domain is assigned in init() function its value differs depending whether it is accessed via a "getter" function getDomain() or directly via domain variable as exposed via modules "public" API.

See the following stripped down code which demonstrates the issue.

var ConfigManager = (function() {

  var privateDomain = 'default';

  function init(dom) {
    privateDomain = dom;
  }

  function getDomain() {
    return privateDomain;
  }

  return {
    init: init,
    domain: privateDomain,
    getDomain: getDomain
  };

})();

console.log(ConfigManager.domain); // Prints 'default'
console.log(ConfigManager.getDomain()); // Prints 'default'

ConfigManager.init('new domain');

console.log(ConfigManager.domain); // Prints 'default' <-- What??
console.log(ConfigManager.getDomain()); // Prints 'new domain'

At this point I am very confused how a variable returned from a getter function can have a different value when it is accessed directly?

Than you in advance!


Solution

  • Since privateDomain is a String, you're not copying / returning the reference, but the value.

    Therefore when you're changing the domain using the init function, it just updates privateDomain, since domain has no link to it other than being a copy.

    Hope it helps! :)