Javascript Object Accessors
JavaScript object accessors, also known as getters and setters, allow you to define methods to retrieve and set the values of an object's properties.
They provide a way to access and manipulate object properties like you would with regular object properties, but with additional functionality.
As an example:
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
},
set fullName(value) {
const parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
},
};
console.log(person.fullName); // Output: "John Doe"
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: "Jane"
console.log(person.lastName); // Output: "Smith"
In this example:
- We define a
person
object withfirstName
andlastName
properties. - We also define
fullName
as an accessor property, which combines thefirstName
andlastName
properties to return a full name string when accessed. - We also define a
set
method for thefullName
property, which splits the full name string into separate first and last name values and sets thefirstName
and lastNam`e properties accordingly.
When we access person.fullName
, the getter method is called and returns the full name string "John Doe"
. When we set person.fullName
to "Jane Smith"
, the setter method is called and sets the firstName
and lastName
properties accordingly.
JavaScript Getter (The get Keyword)
A getter is a function that allows you to retrieve the value of an object's property using dot notation or bracket notation, as if it were a regular property, but with additional functionality.
To define a getter for an object property, you can use the get
keyword followed by the property name and the function definition.
As an example:
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
},
};
console.log(person.fullName); // Output: "John Doe"
In this example
- We define a
person
object withfirstName
andlastName
properties. - We also define a getter for the fullName property using the
get
keyword followed by the function definition. - The getter function returns the full name string by concatenating the
firstName
andlastName
properties.
When we access person.fullName
using dot notation, the getter function is called automatically and returns the full name string "John Doe"
.
Getters can also be used in classes to define computed properties.
As an example:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const rectangle = new Rectangle(10, 5);
console.log(rectangle.area); // Output: 50
In this example:
- We define a
Rectangle
class withwidth
andheight
properties. - We also define a getter for the
area
property using theget
keyword followed by the function definition. The getter function returns the area of the rectangle by multiplying thewidth
andheight
properties.
When we create a new Rectangle
object and access the area
property using dot notation, the getter function is called automatically and returns the area value of 50.
JavaScript Setter (The set Keyword)
A setter is a function that allows you to set the value of an object's property using dot notation or bracket notation, as if it were a regular property, but with additional functionality.
To define a setter for an object property, you can use the set
keyword followed by the property name and the function definition.
As an example:
const person = {
firstName: "John",
lastName: "Doe",
set fullName(value) {
const parts = value.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
},
};
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: "Jane"
console.log(person.lastName); // Output: "Smith"
In this example:
- We define a
person
object withfirstName
andlastName
properties. - We also define a setter for thefullName
property using theset
keyword followed by the function definition. - The setter function takes a string value, splits it into separate first and last name values, and sets the
firstName
andlastName
properties accordingly.
When we set person.fullName
to "Jane Smith" using dot notation, the setter function is called automatically and sets the firstName
and lastName
properties accordingly.
Setters can also be used in classes to define properties with setters.
Here's an example:
class Rectangle {
constructor() {
this._width = 0;
this._height = 0;
}
set width(value) {
this._width = value;
}
set height(value) {
this._height = value;
}
get area() {
return this._width * this._height;
}
}
const rectangle = new Rectangle();
rectangle.width = 10;
rectangle.height = 5;
console.log(rectangle.area); // Output: 50
In this example:
- We define a
Rectangle
class with_width
and_height
properties, which are set to 0 by default. - We also define setters for the
width
andheight
properties using the set keyword followed by the function definition. - The setter functions set the
_width
and_height
properties accordingly.
When we set rectangle.width
and rectangle.height
using dot notation, the setter functions are called automatically and set the _width
and _height
properties accordingly. When we access the area
property using dot notation, the getter function is called automatically and returns the area value of 50.
Why Using Getters and Setters?
Using getters and setters in JavaScript provides several benefits:
Encapsulation
Getters and setters allow you to encapsulate the internal state of an object and control access to it. This helps to protect the object's data from accidental modification or misuse.
Abstraction
Getters and setters allow you to abstract away the implementation details of an object and expose only the essential properties and methods to the outside world. This can make it easier to use and maintain the object.
Validation
Getters and setters allow you to validate and control the data that is stored in an object. For example, you can check that the data is of the correct type, within a valid range of values, or meets other constraints.
Computed properties
Getters allow you to compute and return values based on other properties or methods of an object. This can be useful for providing derived or calculated properties that are based on the object's internal state.
Compatibility with existing code
Using getters and setters is a common pattern in many programming languages and frameworks. By using this pattern in your JavaScript code, you can make it more compatible with other codebases and easier to understand for other developers.
The Object.defineProperty()
Object.defineProperty()
is a built-in method in JavaScript that allows you to define a new property directly on an object or modify an existing one. The method takes three arguments:
The object to define the property on.
The name of the property to define or modify.
An object that specifies the characteristics of the property, including its value, whether it can be modified or deleted, and whether it can be enumerated in a
for...in
loop.
Here's an example of using Object.defineProperty()
to define a new property on an object:
const person = {};
Object.defineProperty(person, "name", {
value: "John",
writable: false,
enumerable: true,
configurable: true,
});
console.log(person.name); // Output: John
person.name = "Jane"; // Throws an error in strict mode because writable is set to false
console.log(person.name); // Output: John
In this example:
- We define a new property named
name
on theperson
object with a value of'John'
. - We set the
writable
property tofalse
, which means the value of the property cannot be changed after it is set. - We also set the
enumerable
property totrue
, which means the property will be included when the object's properties are enumerated in afor...in
loop. - Finally, we set the configurable property to
true
, which means the property can be deleted later using thedelete
operator.