samedi 31 janvier 2015

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?





Aucun commentaire:

Enregistrer un commentaire