1

Can anyone tell the difference between the following two code samples? From the result aspects, they are pretty much the same, but what are the use cases for these two code snippets? Any difference under the hood? Any pitfalls we need to avoid or need to know before we create our object in JavaScript?

var celebrity = {
  celebrityID: 999,
  getID: function ()  {
    return this.celebrityID;
  },
  setID: function (theNewID)  {
    this.celebrityID = theNewID;
  }
}

celebrity.getId(); // 999
celebrity.setId(123);
celebrity.getId(); // 123

Vs.

function celebrity () {
  var celebrityID = 999;
  return {
    getID: function ()  {
      return celebrityID;
    },
    setID: function (theNewID)  {
        celebrityID = theNewID;
    }
  }
}


​var obj = celebrity();
obj.getID(); // 999
obj.setID(123); 
obj.getID(); // 123
  • Possible duplicate of [Which way is best for creating an object in javascript? is "var" necessary before variable of object?](https://stackoverflow.com/questions/6843951/which-way-is-best-for-creating-an-object-in-javascript-is-var-necessary-befor) – Dmitry Sep 30 '17 at 18:15
  • Lookup the terms ("Javascript" and) "scope", "lexical scoping", "private variables" etc. The second example hides `celebrityId`. Read: http://jargon.js.org/_glossary/REVEALING_MODULE_PATTERN.md or https://www.codeproject.com/Articles/1164113/Module-and-Revealing-Module-Patterns-in-JavaScript or many other blog posts about _"revealing module pattern"_ (You do _not_ need to memorize how some people decided to call this specific code pattern - too many people confuse learning words with learning concepts) – Mörre Sep 30 '17 at 19:28
  • Thanks a lot, you are openning a new world for me, I am going to dive in it !!! – logicMonster Oct 01 '17 at 02:14

1 Answers1

1

There is a major difference, from a use-case perspective, in that in the first case celebrityID is public, which means this works:

celebrity.celebrityID = "foo"
celebrity.getID() // foo

This is often undesirable. In the second case celebrityID is private. The only access to it is through the getter/setter:

var obj = celebrity();
obj.celebrityID = "foo";
obj.getID(); // still 999

Another nice thing about the function over the object literal is that you can pass in an argument if you wanted to set the initial value. For example:

function celebrity (val) {
    var celebrityID = val || "Default";
    return {
      getID: function ()  {
      return celebrityID;
     },
     setID: function (theNewID)  {
        celebrityID = theNewID;
     }
   }
  }

var obj = celebrity("Foo");
obj.getID(); // 'Foo'

var obj2 = celebrity();
obj2.getID(); // 'Default'
Mark
  • 90,562
  • 7
  • 108
  • 148