mercredi 8 avril 2020

javascript singleton how to change properties inside a class

I have seen that people use Object.freeze alongside some other techniques to make a class Singleton.

Let's say I have this class.

class Test {
    constructor(){
        this.data = [];
    }

    setData(){
        this.data = [1,2,3];
    }

}

const test = new Test();
Object.freeze(test);
export default test;

Now, I import this into another file.

import Test from './test'
Test.setData();

This now causes error that Cannot assign to read only property to data which means that I can't even use setters/getters for my properties.

Question 1) why do we use Object.freeze if we can't even change properties inside a class?

Question 2) what would i do to be able not to change properties outside a class, but inside a class?

Aucun commentaire:

Enregistrer un commentaire