Video thumbnail for JavaScript Classes _ Getter & Setter Methods In JavaScript explained with Examples

JavaScript Classes _ Getter & Setter Methods In JavaScript explained with Examples

Aug 29, 2023
Getter and setter methods are special methods in JavaScript that are used to get and set the value of a property. Getter methods are called when the property is accessed, and setter methods are called when the property is set. Getter and setter methods are often used to encapsulate the data in an object. This means that the data is hidden from the outside world and can only be accessed through the getter and setter methods. The syntax for a getter method is as follows: get property() { // Body of the getter method } The property is the name of the property. The Body of the getter method is the code that is executed when the property is accessed. The syntax for a setter method is as follows: set property(value) { // Body of the setter method } The property is the name of the property. The value is the new value of the property. The Body of the setter method is the code that is executed when the property is set. The following code defines a class called Person with a getter and setter method for the name property: class Person { constructor(name) { this.name = name; } get name() { return this._name; } set name(value) { this._name = value; } } The Person class has a constructor function that takes a name as a parameter. The constructor function sets the value of the name property to the value of the parameter. The name property has a getter method that returns the value of the property. The name property also has a setter method that sets the value of the property. The _name property is a private property. Private properties are not accessible from outside the class. I hope this summary is helpful. Please let me know if you have any other questions.
Computers & Electronics Programming Java (Programming Language) Software Scripting Languages Computer Education