0

I am trying to learn more about how to create private variables and methods in JavaScript. The code below seems to work but I feel as though there may be a more efficient way to do this. Any suggestions?

var CountObject = (function () {

function countObject() {
    // private variables
    var _a = 1;
    var _b = 2;
    var _c = _a + _b;

    // private method
    addTo = function (num) {
        _c = _c + _a + _b + num;
        return _c;
    }
}

// public method
countObject.prototype.add = function (num) {
    return addTo(num);
};

return countObject;
}());

var testObject1 = new CountObject();

console.log(testObject1.add(1));
//output 7

console.log(testObject1.add(1));
//output 11

console.log(testObject1.add(1));
//output 15

var testObject2 = new CountObject();

console.log("testobject2:" + testObject2.add(100));
//output testobject2:106
Donald J
  • 107
  • 1
  • 5
  • 2
    `addTo` is not a private (local) method, but a global (not even instance-specific) function! You cannot call local functions from the prototype. – Bergi Jun 12 '14 at 14:23
  • What seems inefficient about this code? Think outloud for us – Sterling Archer Jun 12 '14 at 14:23
  • Maybe inefficient was the wrong word to use. I guess "wonky" would be a more appropriate word. The wonky feeling probably comes from the fact I wasn't entirely sure what was going on at first. – Donald J Jun 12 '14 at 14:35

1 Answers1

0

addTo is not a private (local) method, but a global (not even instance-specific) function! Try to do testObject1.add(0) again after having created the testObject2 and you will see it fail.

You cannot call local (constructor-scoped) functions from the prototype, so this seems pointless. Fix it by using an instance-specific, privileged (with access to the local variables) method:

function CountObject() {
    // private variables
    var a = 1;
    var b = 2;
    var c = a + b;

    // public method
    this.add = function (num) {
        c = c + a + b + num;
        return c;
    };
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ok so I guess that's where my confusion comes in, I cannot find a clear difference between a privileged method and a public method. Does attaching to the prototype make it a truly public method? If that is true does that mean the only difference between a privileged method and a public method is the fact the public method is inherited down the prototype chain? – Donald J Jun 12 '14 at 14:31
  • No. *Public* only means that it is a property of the object, not a local-scoped variable. If a [public] property is on the prototype, it means that it is *shared* amongst the instances. If a function is declared in the constructor (where the private variables live), it means it is a closure and has access to the variables - being *privileged* against those without access. See also [Use of 'prototype' vs. 'this' in JavaScript?](http://stackoverflow.com/q/310870/1048572) – Bergi Jun 12 '14 at 14:37