Abdi
Abdi

Reputation: 499

How to freeze properties inside a contructor function in JavaScript

I'm trying to make the properties inside a constructor function immutable, i.e. the properties should not be altered either with a dot or bracket notation. E.g. I have my constructor function:

function OnceNamedOne() {
    Object.freeze(this.firstName = 'John');
    Object.freeze(this.lastName = 'Doe');
    this.fullName = this.firstName + ' ' + this.lastName;
}

I basically want to freeze the properties and hard wire their values as in the function. So, when an instance is created:

var me = new OnceNamedOne(); and when the value I try to change the property value, it should not work - that is the following should not assign 'John' to first name: me.firstName = 'John';.

How could I do this?

Upvotes: 2

Views: 266

Answers (1)

adeneo
adeneo

Reputation: 318222

You can't freeze a property with a primitive, but you could make it non-writable

Object.defineProperty(this, 'firstname', {
  enumerable   : false,
  configurable : false,
  writable     : false,
  value        : 'John'
});

FIDDLE

For multiple properties, it's probably easier to make a convenience function

function createNonWritable(obj, key, value) {
    Object.defineProperty(obj, key, {
          enumerable   : false,
          configurable : false,
          writable     : false,
          value        : value
    });
}

function OnceNamedOne() {
    createNonWritable(this, 'firstname', 'John');
    createNonWritable(this, 'lastname', 'Doe');
    createNonWritable(this, 'fullname', this.firstname + ' ' + this.lastname);
}

FIDDLE

Or as noted in the comments, as the attributes has a default value of false you don't have to explicitly set them to that

function OnceNamedOne() {
    Object.defineProperty(this, 'firstname', {value : 'John'});
    Object.defineProperty(this, 'lastname',  {value : 'Dow'});
    Object.defineProperty(this, 'fullname',  {value : this.firstname + ' ' + this.lastname});
}

Upvotes: 3

Related Questions