views:

50

answers:

3

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

+1  A: 

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

var privateMember = "private value";
Kyle Jones
This was a typo in my question. Problem still happens even when I use var
wheresrhys
+2  A: 

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
+3  A: 

Righto, knew I awnsered something like this before:
http://stackoverflow.com/questions/3617139/private-variables-in-inherited-prototypes/3617325#3617325

;oP

BGerrissen
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