Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access "private" variables in prototype

Tags:

javascript

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?

like image 906
user6669 Avatar asked Nov 02 '12 21:11

user6669


People also ask

Can you access private variables?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

How can you access private variable or function outside the scope?

As mentioned above using person. getSecret() will let you access that private variable from anywhere.

How do I access prototype objects?

Its name is not standard, but in practice all browsers use __proto__ . The standard way to access an object's prototype is the Object. getPrototypeOf() method. When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property.

How do I access private properties in TypeScript?

In TypeScript there are two ways to do this. The first option is to cast the object to any . The problem with this option is that you loose type safety and intellisense autocompletion. The second option is the intentional escape hatch.


1 Answers

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.

like image 182
Alnitak Avatar answered Sep 29 '22 06:09

Alnitak