- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between getter and setter in JavaScript?
Getter
When a property is accessed, the value gets through calling a function implicitly. The get keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
Setter
When a property is set, it implicitly calls a function and the value is passed as an argument. With that, the return value is set to the property itself. The set keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.
Example
Here’s an example showing how to implement both getter and setter
<html> <body> <script> var department = { deptName: "Finance", deptZone: "South", deptID: 105, get details() { return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID; }, set details(info) { var res = info.toString().split(' '); this.deptName = res[0] || ''; this.deptZone = res[1] || ''; this.deptID = res[2] || ''; } } department.details = 'Marketing North 001'; document.write(department.deptName); document.write(department.deptZone); document.write(department.deptID); </script> </body> </html>
Advertisements