- 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
How to define getter and setter functions 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 call 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: "Marketing", deptZone: "North", deptID: 101, get details() { return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID; }, set details(info) { var words = info.toString().split(' '); this.deptName = words[0] || ''; this.deptZone = words[1] || ''; this.deptID = words[2] || ''; } } department.details = 'Marketing North 001'; document.write(department.deptName); document.write(department.deptZone); document.write(department.deptID); </script> </body> </html>
Advertisements
To Continue Learning Please Login
Login with Google