Home > Blockchain >  What is the better way of changing a property of an instance of a class using JavaScript's clas
What is the better way of changing a property of an instance of a class using JavaScript's clas

Time:07-11

Lets say I have a simple class that looks like this:

class Person {
    constructor(name) {
        this.name = name;
    }
}

Then I initialize a single instance of that class:

const test = new Person('George');

But then I decide that I want to change the name of that instance and I wonder if I should create a function of that class that takes a name as an argument and then sets it like this:

class Person {
    constructor(name) {
        this.name = name;
    }

    const setName = (newName) => {
        this.name = newName;
    }
}

And then changing the name of the instance through the function like this:

test.setName('John');

Or just straight up change the name of the instance like this:

test.name = newName

CodePudding user response:

If the question is:

What is the better way of changing a property of an instance of a class using JavaScript's class syntax?

the answer would be

using getters and setters

class Person {
  #name;//declare private property by prefix it with hash
  constructor(name) {
    this.#name = name;
  }
  set name(val) {
    this.#name = val;
  }

  get name() {
    return this.#name;
  }
}
let test = new Person('John');
test.name = "Mehdi";
console.log(test.name);

Update: adding private properties to make sense using getters and setters

Note: JS implement private properties in ES2022.

CodePudding user response:

There are no public/private keywords for properties like in other languages. Technically nothing is stopping you from doing it.

BUT

Using getters and setters allows you to add a level of abstraction.

For example, if later you want to add the fact that the names are not longer than 10 characters. You will just have to modify the setName() function and it will affect all calls. If you had used the direct method, you would have had to modify all the places where you used it.

  • Related