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

2
  • 1
    Should be using Object2.prototype = Object1(), or is that just a typo in the pasted code? Commented Sep 14, 2010 at 14:35
  • possible duplicate of Private variables in inherited prototypes Commented Sep 14, 2010 at 14:47

3 Answers 3

3

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

;oP

Sign up to request clarification or add additional context in comments.

1 Comment

I knew it had to have been asked before, but just couldn't find the right phrase to search for. Cheers for the answer
2

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

var privateMember = "private value";

1 Comment

This was a typo in my question. Problem still happens even when I use var
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; 
}(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.