Accessors: Getters and Setters
Getter (The get
Keyword)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const person = {
firstName: 'Noorain',
lastName: 'Khan',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
};
// Accessing the getter
console.log(person.fullName); // Output: Noorain Khan
</Script>
</body>
</html>
Output: Noorain Khan
Setter (The set
Keyword)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const person = {
firstName: 'Arshiya',
lastName: 'Naaz',
set fullName(name) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
// Using the setter
person.fullName = 'Jane Smith';
console.log(person.firstName); // Output:Arshiya
console.log(person.lastName); // Output: Naaz
</Script>
</body>
</html>
Output:
First Name: Arshiya
Last Name: Naaz
Combining Getter and Setter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<Script>
const person = {
firstName: 'Arshiya',
lastName: ' Naaz',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(name) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
// Using getter and setter
console.log(person.fullName); // Output: Arshiya Naaz
person.fullName = 'Anam Fatema';
console.log(person.fullName); // Output: Anam Fatema
</Script>
</body>
</html>
Output:
Initial Full Name: Arshiya Naaz
Updated Full Name: Anam Fatema