Mutators
A mutator method (also known as a setter) can be used to prevent direct modification of a member variable by creating a private variable . This method determines the behavior when assigning a value to those variables.
In Javascript, private member variables are prefixed using the #
symbol, while mutators are created with the set
keyword.
class Animal {#name;set name(name) {this.#name = name;}}const someAnimal = new Animal();
The value of the private variable can now be updated by assigning a new value.
Note: The value of the private variable can not be retrieved without an accessor (also known as a getter).
class Animal {#name;set name(name) {this.#name = name;}}const someAnimal = new Animal();someAnimal.name = 'Buddy';console.log(someAnimal.name);
The example above results in the following output:
undefined
Attempts to access a private variable using the #
prefix will result in a syntax error.
class Animal {#name;set name(name) {this.#name = name;}}const someAnimal = new Animal();someAnimal.name = 'Buddy';console.log(someAnimal.#name);
The example above results in the following output:
SyntaxError: Private field '#name' must be declared in an enclosing class
Codebyte Example
This example shows how to update and retrieve the value of a private variable.
All contributors
- karel.de.smetoutlook.com7 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.