4

[Yes, I have read several answers to similar questions, but didn't really get the answer I'm looking for, so I'm going to ask my question anyway.]

In the code below, how can I place the methods setSecret and tellSecret in Secret's prototype while still maintaining access to the private instance variable _secret, and also producing the same output?

I tried this (see jsbin) which placed the methods in the prototype, but changed the output.

function Secret() {

    // ===== private =====

    var _secret;

    // ===== public =====

    this.setSecret = function (secret) {
        _secret = secret;
    };

    this.tellSecret = function () {
        console.log(_secret);
    };
}

var secretA = new Secret();
var secretB = new Secret();

secretA.setSecret("AAA");
secretB.setSecret("BBB");

setTimeout(function () {
    console.log("Secret A");
    secretA.tellSecret();

    console.log("Secret B");
    secretB.tellSecret();
}, 1000);


// ===== output =====

Secret A
AAA
Secret B
BBB
RBR
  • 999
  • 3
  • 13
  • 24
  • 2
    You can't. There are no "private instance variables" in JavaScript. `_secret` is a local variable, so only functions defined inside the constructor can access it. End of story. – Felix Kling Feb 03 '14 at 06:38
  • possible duplicate of [javascript - accessing private member variables from prototype-defined functions](http://stackoverflow.com/questions/436120/javascript-accessing-private-member-variables-from-prototype-defined-functions) – Felix Kling Feb 03 '14 at 06:39
  • Felix, by "private instance variables" I mean in closure scope. See jsbin link above- I am able to access _secret from prototype methods, but the output changes, i.e. the second instance's secret overwrites the first instance's secret. – RBR Feb 03 '14 at 07:31
  • I know what you mean. But it's just not possible, at least not with current implementations. There are a couple of other related questions: https://stackoverflow.com/questions/17220653/is-there-a-way-in-javascript-to-give-access-to-variable-inside-a-prototype-priva, https://stackoverflow.com/questions/9572029/implementing-private-instance-variables-in-javascript, https://stackoverflow.com/questions/8580540/javascript-calling-private-method-from-prototype-method, https://stackoverflow.com/questions/6307684/how-to-create-private-variable-accessible-to-prototype-function, – Felix Kling Feb 03 '14 at 07:44
  • What is just not possible? Please be specific. – RBR Feb 03 '14 at 08:11
  • What you asked for: *"Accessing Private Instance Variable from Prototype Method"* – Felix Kling Feb 03 '14 at 08:46
  • @Felix. Yep, that's the topic, BUT my question is not just about accessing _secret. Access itself is possible- i.e. I am able to access _secret from a prototype method - see http://jsbin.com/odUzAWUB/2/edit?js,console. My question is, how to do it without changing the output from when I access it from a method in the constructor itself. How to make it so instances of Secret don't override each others' secrets. – RBR Feb 03 '14 at 18:49
  • That's what I'm trying to say: It's not possible. – Felix Kling Feb 03 '14 at 19:28
  • @Felix. Glad I explained what you meant then. Thanks. – RBR Feb 03 '14 at 21:35

4 Answers4

6

Simply put, you shouldn't use private variables with prototype methods. Trying to mix the two requires awful workarounds, and there are better alternatives.
Here's an explanation why. (This is an excerpt from a similar answer: https://stackoverflow.com/a/21522742/272072)

Prototypal Methods

In JavaScript, prototype methods allows multiple instances to share a prototype method, rather than each instance having its own method.
The drawback is that this is the only thing that's different each time the prototype method is called.
Therefore, any "private" fields must be accessible through this, which means they must also be publicly accessible. So, the best we can do is to stick to naming conventions for _private fields.

Mixing with Private Variables

When you use a closure to create a private variable, you cannot access it from a prototypal method unless it's exposed through the this variable. Most solutions, therefore, just expose the variable through method, which means that you're exposing it publicly one way or another.

Just use conventions for _private fields

So, I think using _private fields makes the most sense, even though they're still public. It makes debugging easier, provides transparency, could improve performance, and so that's what I usually use.
Stick to conventions for _private fields and everything goes great.
And I just don't understand why JS developers try SO hard to make fields truly private.

Community
  • 1
  • 1
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
  • "Most solutions, therefore, just expose the variable through method, which means that you're exposing it publicly one way or another." Yes, these are called accessors, and are a valid use case when you want to control access to a variable (eg. no set, only get, or some validation logic before set). – Asad Saeeduddin Sep 13 '14 at 17:47
  • 1
    "And I just don't understand why JS developers try SO hard to make fields truly private." Because we don't trust other developers not to eff with our variables in really stupid ways! – Grinn Dec 10 '14 at 16:50
1

this one is related to Alon's answer, but by implementing a WeakMap, doesn't reveal an identifying index and won't accumulate un-used objects. While a better solution in terms of efficiency, it's not as good an answer in terms of compatibility. WeakMaps are supported in FireFox and Chrome and Node.JS, so i feel they are worth mentioning.

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap for more info.

var Secret = (function(){

   var secrets=new WeakMap();

  function Secret() {

    // ===== private =====

    secrets.set(this, null);

   // ===== public =====

   }

    Secret.prototype.setSecret = function (secret) {
       secrets.set(this, secret);
    };

    Secret.prototype.tellSecret = function () {
        console.log(secrets.get(this));
    };


   return Secret;

}());


var secretA = new Secret();
var secretB = new Secret();

secretA.setSecret("AAA");
secretB.setSecret("BBB");

setTimeout(function () {
    console.log("Secret A", secretA  );
    secretA.tellSecret();

    console.log("Secret B", secretB );
    secretB.tellSecret();
}, 1000);
dandavis
  • 16,370
  • 5
  • 40
  • 36
0

This is an incredibly ugly solution, and you probably shouldn't use it, but it works. Based on this answer.

var Secret = (function () {
    var instance = 0,
        p = [];

    function Secret() {
        this.i = instance++;
        p[this.i] = {};
        p[this.i]._secret = null;
    }

    Secret.prototype.setSecret = function (secret) {
        p[this.i]._secret = secret;
    };

    Secret.prototype.tellSecret = function () {
        console.log(p[this.i]._secret);
    };

    return Secret;
})();

var secret = new Secret();
secret.setSecret("A");

var secret2 = new Secret();
secret2.setSecret("B");

console.log(secret._secret)  // => undefined

secret.tellSecret()          // => A
secret2.tellSecret()         // => B
Community
  • 1
  • 1
Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288
  • You should mention that the content of `p` would not be automatically gc, but that the content would stay in memory until the page/applications is reloaded. – t.niese Feb 03 '14 at 06:59
0

Try this, and tell me if it's what you search.
To make more interesting the snippet I added more 2 private properties to your object Secret
(Note that all your private vars are really private)

function Secret() {
  // ===== private ===== 
  var _properties = { secret:null, secret2:null, secret3:null } // <-- Put all yours properties here

  // ===== public =====
  this.getset = function(PROP, V) { 
        if(typeof V !== "undefined") _properties[PROP]=V; return _properties[PROP]; 
  }
}

 // Create GETTER & SETTER for each of yours properties
 MAKE_GET_SET(Secret, "secret", true, true);    // get and set 
 MAKE_GET_SET(Secret, "secret2", true, true);   // only set
 MAKE_GET_SET(Secret, "secret3", true, false);  // only get


/* === "Magic function" ;-) to create new properties's GETTER & SETTER ============= */
function MAKE_GET_SET(OBJ, PROPNAME, makeGET /* boolean */, makeSET /* boolean */) {  
      Object.defineProperty( OBJ.prototype, PROPNAME, { 
        get: function() { return makeGET ? this.getset(PROPNAME) : null; }, 
        set: function(V) { if(makeSET) this.getset(PROPNAME,V); }, 
        enumerable: true
      } );
} 
/* ================================================================================= */

var secretA = new Secret();
var secretB = new Secret();

secretA.secret = "AAA";  // <-- here use setter
secretB.secret = "BBB";  // <-- here use setter

setTimeout(function () {
    console.log("Secret A: "+secretA.secret);  // <-- here use getter
    console.log("Secret B: "+secretB.secret);  // <-- here use getter
}, 1000);

/* ===== output =====

Secret A: AAA
Secret B: BBB

 ===== output ===== */