5

Is it possible in JavaScript to create a private variable which can be accessed in prototype? I tried the following which obviously doesn't work, because bar is only accessible from within Foo and not from within prototype.

function Foo() {
    var bar = 'test';
}

Foo.prototype.baz = function() {
    console.log(bar);
};

I know I also cannot use this.bar = 'test', because that would make the property public AFAIK. How to make the bar variable private, but accessible by prototype?

4
  • Not unless you return it (which means it isn't exactly private, but still is)! Commented Nov 2, 2012 at 21:46
  • What do you mean by "public"? What's your use case for this? Commented Nov 2, 2012 at 21:48
  • @AndyRay The use case is encapsulation in general and how it is handled in JavaScript in specific. Commented Nov 2, 2012 at 21:52
  • If you're not instantiating Foo with new then you can just do Foo.prototype.bar = 'whatever'; and Foo.bar won't exist. But if you do var q = new Foo(); then q.bar will exist Commented Nov 2, 2012 at 22:02

1 Answer 1

10

You can't - it's impossible to access a lexically scoped variable from outside that scope.

Prototype methods are (by definition) shared between all instances, and to do so must exist in their own scope.

Douglas Crockford's article Private Members in JavaScript provides some useful explanations, but no solution that meets your requirements.

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

3 Comments

It is possible (and not even hard) to create a variable accessible to some methods within the prototype.
Care to elaborate on this? @JanDvorak Or am I just doing something stupid and is this just not how JavaScript should work?
Apologies, my variables would be "class" variables, not "instance" variables. That's not what's requested. I was thinking of privileged methods - moving them to the prototype would create "static" variables. Upvoting.

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.