Javascript — Immutable types

In C# and oth­er sim­i­lar gen­er­al pur­pose lan­guages, there are access mod­i­fiers which allow you to spec­i­fy whether a par­tic­u­lar prop­er­ty can be accessed/modified by every­one (pub­lic), only sub­class­es (pro­tect­ed) or only from with­in the same class (pri­vate).

In these lan­guages, cre­at­ing an immutable type usu­al­ly involves:

  • mak­ing all prop­er­ties pub­licly get­table
  • mak­ing all prop­er­ties pri­vate­ly set­table
  • con­struc­tor takes in all the nec­es­sary para­me­ters to ini­tial­ize the prop­er­ties

Here’s an exam­ple of an immutable class in C#:

public sealed class Dog
    public Dog(string name, string breed, int age)
        Name = name;
        Breed = breed;
        Age = age;

    public string Name { get; private set; }

    public string Breed { get; private set; }

    public int Age { get; private set; }

Javascript, how­ev­er, do not have an equiv­a­lent of the pri­vate key­word, in fact, all the mem­bers of an object are pub­lic. So, to achieve the same effect in javascript you can use local vari­ables instead and cre­ate an acces­sor method (i.e. get­ters) for each.

Here’s the equiv­a­lent object in javascript:

function Dog(name, breed, age) {
    // use local variables so that they can't be access from outside
    var _name = name, _breed = breed, _age = age;

    // define accessor methods
    this.getName = function () {
        return _name;

    this.getBreed = function () {
        return _breed;

    this.getAge = function () {
        return _age;

And to use it:

var obj = new ImmutableObject("Dusty", "Highland Terrier", 2);
alert("Name: " + obj.getName() + ", Age: " + obj.getAge() + ", Breed: " + obj.getBreed());

Have a read through Dou­glas Crock­ford’s arti­cle on pri­vate mem­bers in javascript (see ref­er­ence below), it goes into much more depth to explain the object mod­el of javascript and the pat­terns for pro­duc­ing pub­lic, pri­vate and priv­i­leged mem­bers.


Dou­glas Crock­ford — pri­vate mem­bers in JavaScript