user6669
user6669

Reputation: 155

Access "private" variables in prototype

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?

Upvotes: 5

Views: 247

Answers (1)

Alnitak
Alnitak

Reputation: 339786

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.

Upvotes: 10

Related Questions