📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
JavaScript Class - Getters and Setters
- firstName
- lastName
- emailId
- age
JavaScript Class - Getters and Setters Example
class User {
constructor(firstName, lastName, emailId, age) {
this._firstName = firstName;
this._lastName = lastName;
this._emailId = emailId;
this._age = age;
}
set firstName(firstName) {
this._firstName = firstName;
}
get firstName() {
return this._firstName;
}
set lastName(lastName) {
this._lastName = lastName;
}
get lastName() {
return this._lastName;
}
set emailId(emailId) {
this._emailId = emailId;
}
get emailId() {
return this._emailId;
}
set age(age) {
this._age = age;
}
get age() {
return this._age;
}
}
let user = new User('Ramesh', 'Fadatare', 'ramesh@gmail.com', 29);
console.log('Before changing attributes of User object');
console.log(JSON.stringify(user));
// change first name
user.firstName = 'Ram';
console.log(user.firstName);
// change last name
user.lastName = 'Stark';
console.log(user.lastName);
console.log('After changing attributes of User object');
console.log(JSON.stringify(user));
Before changing attributes of User object
{"_firstName":"Ramesh","_lastName":"Fadatare","_emailId":"ramesh@gmail.com","_age":29}
Ram
Stark
After changing attributes of User object
{"_firstName":"Ram","_lastName":"Stark","_emailId":"ramesh@gmail.com","_age":29}
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:
Learn more about Javascript at JavaScript Tutorial
Comments
Post a Comment
Leave Comment