Essential Tips for Using JavaScript Class Setter and Getter Method in Hindi

📔 : Java Script 🔗

बैसे तो class में हम methods को define और call कर सकते हैं , लेकिन methods को और अच्छी तरह से use करने के लिए हमारे पास setter और getter Methods भी होते हैं।

Actually setter और getter methods को use करने का मैं purpose code को clean और standardize तरीके से utilize करना है।

बैसे तो Java / C++ जैसी truly object oriented programming languages में setter और getter methods का main purpose encapsulation को achieve करना होता है।

***

अब हालाँकि JavaScript में Encapsulation जैसे concept को support करने के बाकि language की तरह कोई define करने का तरीका नहीं है। इसलिए Encapsulation को Closures functions का use करके achieve किया जाता है।

JS Setter and Getter Example

class Circle { constructor(radius) { this._radius = radius; // Private property, indicated by the underscore } // Getter method to get the radius get radius() { return this._radius; } // Setter method to set the radius set radius(newRadius) { if (newRadius >= 0) { this._radius = newRadius; } else { console.log("Radius cannot be negative."); } } // Getter method to get the area of the circle get area() { return Math.PI * this._radius * this._radius; } }

JavaScript में private properties को define करने के लिए कोई special keyword या कोई method नहीं है but हाँ इन्हे indicate करने के लिए underscore का use किया जाता है। जैसा की आपने ऊपर example में देखा।

Calling Getter Method

const circle = new Circle(5); // Using the getter to get the radius and area console.log(circle.radius); // Output: 5 console.log(circle.area); // Output: 78.53981633974483 // Using the setter to update the radius circle.radius = 7; console.log(circle.radius); // Output: 7 // Trying to set a negative radius (setter will handle it) circle.radius = -2; // Output: Radius cannot be negative. console.log(circle.radius); // Output: 7 (radius remains unchanged)

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers