Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a javascript class with immutable properties

This question is specifically about preventing unwanted properties from being added to a javascript "class". I have a class called Animal.

function Animal(){
this.name="";
this.type="";
//20 other properties
}

What would be the easiest way for a user to create their own Animal and add 20 properties. I want to also prevent the user from accidentally adding incorrect properties.

my current method:

    var myAnimal= new Animal();
    myAnimal.name="fluffy";
    myAnimal.type="cat";
    myAnimal.typo="cat";

//adding 20 more properties would require typing myAnimal 20 more times Plus if a user makes a typo it would add it as a new property.

I was hoping there would be something like this:

myAnimal=new Animal{
name:"fluffy",
type:"cat";
typo:"cat" //would throw an error
}

I've looked into Object.freeze Object.seal, Object.preventExtensions but not sure how they apply to classes.

like image 609
techdog Avatar asked Feb 07 '18 23:02

techdog


People also ask

How can I create immutable property in a JavaScript object?

You can freeze (make immutable) an object using the function Object. freeze(obj) . The object passed to the freeze method will become immutable. The freeze() method also returns the same object.

How can I get immutability in JavaScript?

To make objects and arrays immutable you can use some techniques in JavaScript and create new values without modifying the original content. Do not change the original value of an object directly. Treat this object as immutable and return a completely new object with the updated value.

How do you make a variable immutable in JavaScript?

The const keyword only creates a read-only reference to a value, which means that the value cannot be reassigned. As the MDN reference says: The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.


1 Answers

You can Object.seal(this) at the end of the constructor to prevent new properties from being added:

function Animal() {
    this.name = "";
    this.type = "";
    // 20 other properties
    Object.seal(this);
}

and you can take an object with initial values in the constructor:

function Animal(initial) {
    this.name = "";
    this.type = "";
    // 20 other properties
    Object.seal(this);
    Object.assign(this, initial);
}

used like so:

myAnimal = new Animal({
    name: "fluffy",
    type: "cat",
    typo: "cat",
});

with the downside that the error doesn’t point directly at typo like it would if you used multiple assignment statements.

like image 96
Ry- Avatar answered Oct 04 '22 03:10

Ry-