2

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!

ChrisR
  • 3,922
  • 1
  • 14
  • 24
Konaras
  • 573
  • 6
  • 14

2 Answers2

3

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! :)

FatalMerlin
  • 1,463
  • 2
  • 14
  • 25
  • 1
    Ahh... i see. I knew that javascript is passed by value (same as Java), but thought since strings are objects their variables would be pointing to the same string object. I should probably research a bit more how strings are handled in JS. Thanks. – Konaras Jul 25 '18 at 13:04
  • @Konaras It's a learning journey, and I also started with Java. The difference is quite confusing at times. Glad I could help! :) Also because of its occasional "weirdness" JS is just more powerful, at least from my point of view. – FatalMerlin Jul 25 '18 at 13:07
2

It's because when domain is returned, it's value is still "default". It's how Javascript works, more info here: Javascript by reference vs. by value

But when you use the function "getDomain" you will get the updated value.

Also have a look at the get/set syntax: Getter

ChrisR
  • 3,922
  • 1
  • 14
  • 24
  • Yes this appears to be be correct answer too. Thanks. Also thanks for heads-up about the getter syntax, seems to be exactly what i need! – Konaras Jul 25 '18 at 13:05