2

I'm setting up my javascript objects like the following

Object1 = function() {
  var privateMember = "private value"

  return {
    publicMember: "public value"
    setPrivateMember: function(value) {
       privateMember = value;
    }
  }
}();

Now if I use prototypal inheritance to create new objects

Object2.prototype = Object1

And then set the private member

Object2.setPrivateMember("new value");

Then the value of private member in Object 1 changes too, so it behaves more like a static variable. Is there a way I can get private variables to not be static?

PS - I'm a self-taught programmer so my use of terminology might be a bit sketchy. Let me know if it needs clarifying

wheresrhys
  • 22,558
  • 19
  • 94
  • 162
  • 1
    Should be using `Object2.prototype = Object1()`, or is that just a typo in the pasted code? – MooGoo Sep 14 '10 at 14:35
  • possible duplicate of [Private variables in inherited prototypes](http://stackoverflow.com/questions/3617139/private-variables-in-inherited-prototypes) – TM. Sep 14 '10 at 14:47

3 Answers3

3

Righto, knew I awnsered something like this before:
Private variables in inherited prototypes

;oP

Community
  • 1
  • 1
BGerrissen
  • 21,250
  • 3
  • 39
  • 40
  • I knew it had to have been asked before, but just couldn't find the right phrase to search for. Cheers for the answer – wheresrhys Sep 14 '10 at 14:40
2

You're creating a global variable. Put var before it.

var privateMember = "private value";
Kyle Jones
  • 536
  • 3
  • 5
2

Edited my answer, can you check if this works?

Try this -

Object1 = function() {  
  var privateMember = "private value"; 

  var returnVal =  {  
                publicMember: "public value",  
                setPrivateMember: function(value) {  
                privateMember = value;  
                }

           }; 
  return returnVal; 
}(); 
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103