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!

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
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

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.