Alex_wd
Alex_wd

Reputation: 13

Javascript simulate real private variable and manage it with getter/setter

Do I use correctly simulation of private variable with this way?

var C = function(a) {
    var _private = a + 1;
    // more code...
    Object.defineProperties(this, {
        'privateProp': {
            get: function() {
                return _private;
            },
            set: function(b) {
                _private = b + 2;
            }
        }
    });
}

So with the getter/setter I can manage that private variable. And value of it can be get/set with custom methods.

Let's say this example

var c = new C(5);

console.log(c.privateProp); // 6
c.privateProp = 2;
console.log(c.privateProp); // 4

Upvotes: 1

Views: 749

Answers (1)

Dan Prince
Dan Prince

Reputation: 29999

There is no correct way to simulate private variables, because they are not part of the Javascript specification.

However, there are still a number of ways to simulate them:

With Getters and Setters

This is the same as your answer but with a slightly different syntax:

function Rocket() {
  var _fuel = 100;

  return {
    get fuel() {
      return _fuel;
    }
    set fuel(value) {
      _fuel = value;
    }
  };
}

This syntax allows you to define the getter and setter functions in a more natural way, but comes with the restriction that they must be inside an object literal.

With a Closure

function Rocket() {
  var fuel = 100;

  return {
    getFuel: function() { return fuel; },
    setFuel: function(value) { fuel = value; }
  };
}

This is arguably the most elegant way, because this is how Javascript has worked ever since anonymous functions were added to the specification.

By Convention

function Rocket() {
  this._fuel = 100;

  this.getFuel = function() {
    return this._fuel;
  };

  this.setFuel = function(value) {
    this._fuel = value;
  };
}

The final way is to expose the variable as public, but mark it as private by using an underscore at the beginning of the name.

Upvotes: 7

Related Questions