0

Consider this:

  var Foo = function Foo () {
      var numberVar = 0;

      fooPrototype = {
          getNumberVar: function () {
                return numberVar;
          },
          setNumberVar: function (val) {
                this.numberVar = val;
          }
      }
      return fooPrototype;
  };

  var foo = new Foo();

Alternatively, look at this:

  var Bar = function Bar() {
        var numberVar = 0;
  };

  Bar.prototype = {
      getNumber: function () {
          return this.numberVar;
      },
      setNumber: function (val) {
          this.numberVar = val;
      }
  };

  var bar = new Bar();

They both do the same thing, in that they allow for public / private members. Is there any benefit to doing this one way or the other?

j08691
  • 190,436
  • 28
  • 232
  • 252
Dave Voyles
  • 3,945
  • 3
  • 23
  • 43

1 Answers1

1

Your logic here is based on a faulty assumption. In your second implementation, the constructor variable numberVar is never used. You have no code that can reach it and thus you are not using a private variable in the second code block.

Your methods in that second implementation are accessing an object property named numberVar which is publicly accessible as a property on the object which is different than the local variable of the same name in your constructor. You cannot have private variables in your second implementation because your prototype-declared methods are not declared in a private scope.

Here's what happens in your second code block:

  var Bar = function Bar() {
        // this variable is never used as there is no code in this scope
        // that can reach this variable.  In fact, it is garbage collected
        // immediately
        var numberVar = 0;
  };

  Bar.prototype = {
      getNumber: function () {
          return this.numberVar;
      },
      setNumber: function (val) {
          // sets a public property on the object
          this.numberVar = val;
      }
  };

  var bar = new Bar();
  bar.setNumber(10);
  console.log(bar.numberVar);    // 10, this property is public

For a general discussion of methods declared in the constructor vs. prototype-defined methods, see this discussion:

Advantages of using prototype, vs defining methods straight in the constructor?

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • Very well said! That post is exactly what I was looking for. Moreover, your second paragraph really helped me to understand what the issue was. Thank you. – Dave Voyles Sep 27 '15 at 15:18
  • Also found a great answer on how to create public / private methods while still using Prototype: https://stackoverflow.com/questions/1441212/javascript-instance-functions-versus-prototype-functions/1441692#1441692 – Dave Voyles Sep 27 '15 at 18:13