Say I have a javascript function/class called Foo
and it has a property called bar
. I want the value of bar
to be supplied when the class is instantiated, e.g:
var myFoo = new Foo(5);
would set myFoo.bar
to 5.
If I make bar
a public variable, then this works, e.g:
function Foo(bar)
{
this.bar = bar;
}
But if I want to make it private, e.g:
function Foo(bar)
{
var bar;
}
Then how would I set the value of the private variable bar
such that its available to all internal functions of foo
?
One of the best tutorials on private and protected access in javascript is here: http://javascript.crockford.com/private.html.
One way I can think of is to use a closure that's assigned to a name and returns a new object. You would pass in any arguments to the constructor through the call to the closure. That would end up being something like the following:
This way, a and b are always declared uniquely. You would then construct your object like so:
If you are willing to use ES2015 classes,
with ESNext, you can use Javascript private variables like this:
Private field #bar is not accessible outside Foo class.
I recently had a similar issue but wanted to use accessor properties also. Below is a Foo(Bar) example based on what I came up with for a solution. This example is trivial but can easily be expanded upon using more complex get/set functions.
You have to put all functions that need to access the private variable inside the constructor: