How to set javascript private variables in constructor?

Viewed 35279

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?

7 Answers

If you are willing to use ES2015 classes,

with ESNext, you can use Javascript private variables like this:

class Foo {
  #bar = '';
  constructor(val){
      this.#bar = val;
  }
  otherFn(){
      console.log(this.#bar);
  }
}

Private field #bar is not accessible outside Foo class.

In ES6+ terms the proper way to do this is as shown in the @Nitin Jadhav's answer. However if for some reason you would like to stick with the good old constructor functions it could be achieved like;

function Foo(val){
  function Construct(){};
  Construct.prototype = { set bar(_){} // you may throw an error here
                        , get bar(){return val;}
                        };
  return new Construct();
};

So two things happen here.

  1. You don't populate the instances of Foo with properties like in the accepted answer.
  2. Unlike the Private Class Fields abstraction you are free to throw an error or not when someone tries to access the private variable through the setter.

Perhaps you would like a private field of the instance itself instead of accessing it through the prototype. Then you may do like;

function Foo(val){
  Object.defineProperty(this,"bar",{ set: function(){}
                                   , get: function(){return val;}
                                   });
};
Related