← Back to JavaScript Course | Chapter 2: Functions & Objects | Lesson 8 of 10

JS Object के Get/Set

Getter और setter methods किसी property को बाहर से एक साधारण value जैसा व्यवहार करने देते हैं, जबकि असल में वह पढ़े या लिखे जाने पर custom code चलाती है -- तुरंत एक derived value calculate करना, या store होने से पहले किसी value को validate और transform करना, यह सब उस property का इस्तेमाल करने वाले के लिए अदृश्य रहते हुए।
Syntax
javascript
const objectName = {
  get propertyName() {
    return value;
  },
  set propertyName(newValue) {
    // assign
  }
};

Getter परिभाषित करना

Getter, जो object literal या class के भीतर get propertyName() { ... } के रूप में लिखा जाता है, अपनी function body को अपने-आप तब चलाता है जब वह property पढ़ी जाती है -- बाहर से, यह ठीक साधारण property की तरह दिखता और व्यवहार करता है, उसे call करने के लिए कोष्ठकों की ज़रूरत नहीं।

Note: किसी भी ऐसे value के लिए getter का उपयोग कीजिए जो हमेशा अन्य properties से ताज़ा गणना होकर आना चाहिए, हर बार कुछ बदलने पर उसे हाथ से दोबारा गणना करके अलग store करने की बजाय।
Warning: A getter is accessed like a plain property (obj.propertyName), not called like a method (obj.propertyName()) -- adding parentheses would try to call whatever the getter returns.

उदाहरण: Defining a Getter

javascript
const circle = {
  radius: 5,
  get area() { return Math.PI * this.radius ** 2; },
};
console.log(circle.area); // no parentheses, looks like a property

Setter परिभाषित करना

Setter, जो set propertyName(value) { ... } के रूप में लिखा जाता है, अपनी function body को अपने-आप तब चलाता है जब वह property assign की जाती है -- जो आपको assign किए गए value को validate, transform या redirect करने देता है इससे पहले कि आप तय करें कि उसे असल में कैसे (या क्या) store करना है।

Note: हर assignment पर अपने-आप किसी validation नियम को लागू करने या transformation (जैसे whitespace हटाना) करने के लिए setter का उपयोग कीजिए, हर बुलाने वाले के इसे याद रखने पर निर्भर रहने की बजाय।
Warning: A setter must be paired with some way to actually store the value (usually a differently-named backing property) -- a setter with no storage logic silently discards whatever is assigned.

उदाहरण: Defining a Setter

javascript
// Declare the constant `user`; its value is built below
// Declare the constant `user`; its value is built below
const user = {
  _age: 0,
  // Define the setter `age` taking `value`
  // Define the setter `age` taking `value`
  set age(value) {
    if (value < 0) throw new Error("Age cannot be negative");
    // Assign `value` to `this._age`
    // Assign `value` to `this._age`
    this._age = value;
  },
};
// Assign `25` to `user.age`
// Assign `25` to `user.age`
user.age = 25;
// Print `user._age` to the console
// Print `user._age` to the console
console.log(user._age);

एक ही Property के लिए Getter और Setter को मिलाना

एक ही property नाम के लिए get और set दोनों परिभाषित करना उसे पूरी तरह कस्टम, validated, computed property की तरह व्यवहार करने देता है -- बाहर से ठीक साधारण property की तरह पढ़ने और लिखने योग्य, जबकि दोनों दिशाओं में पर्दे के पीछे आपका अपना logic चलता है।

Note: जब भी किसी property को कस्टम पढ़ने और कस्टम लिखने दोनों का व्यवहार चाहिए, getter और setter को साथ जोड़िए, और backing storage property को साफ़ अलग तथा एकसमान नाम वाली रखिए।
Warning: Forgetting to define a setter for a property that also has a getter means any assignment attempt is silently ignored (or throws under strict mode), which can be confusing if not intentional.

उदाहरण: Combining a Getter and Setter for the Same Property

javascript
// Declare the constant `temperature`; its value is built below
// Declare the constant `temperature`; its value is built below
const temperature = {
  _celsius: 0,
  get fahrenheit() { return this._celsius * 9 / 5 + 32; },
  set fahrenheit(value) { this._celsius = (value - 32) * 5 / 9; },
};
// Assign `100` to `temperature.fahrenheit`
// Assign `100` to `temperature.fahrenheit`
temperature.fahrenheit = 100;
// Print `temperature._celsius` to the console
// Print `temperature._celsius` to the console
console.log(temperature._celsius);

Classes में Getters और Setters

Class के भीतर, get और set methods ठीक वैसे ही काम करते हैं जैसे object literal में -- class पर एक बार परिभाषित होकर, वे अपने-आप हर instance पर लागू होते हैं, जिससे उस class के हर object को हर instance के लिए logic दोहराए बिना एकसमान computed या validated property व्यवहार मिलता है।

Note: Getters और setters को class के हिस्से के रूप में परिभाषित कीजिए जब उस class के हर instance को किसी property के लिए वही computed या validated व्यवहार साझा करना चाहिए।
Warning: A class getter/setter pair that references this._propertyName still needs each instance's constructor to actually initialize that backing property, or reads may return undefined.

उदाहरण: Getters and Setters in Classes

javascript
// Define the class `Circle`
// Define the class `Circle`
class Circle {
  constructor(radius) { this.radius = radius; }
  get area() { return Math.PI * this.radius ** 2; }
}
// Print `new Circle(3).area` to the console
// Print `new Circle(3).area` to the console
console.log(new Circle(3).area);

Getters/Setters बनाम साधारण Properties कब

जब किसी गणना या validation की ज़रूरत न हो तब साधारण property ज़्यादा सरल और पर्याप्त है -- getter/setter पर विशेष रूप से तब जाइए जब property को अन्य data से निकाला जाना हो, या हर assignment पर कोई नियम लागू करना हो, उस logic को एक जगह रखते हुए बजाय इसके कि वह हर उस जगह बिखरा हो जहाँ value सेट की जाती है।

Note: डिफ़ॉल्ट रूप से साधारण properties से शुरू कीजिए, और getter/setter जोड़ी में तभी बदलिए जब आपको उस विशिष्ट property के लिए सचमुच computed या validated व्यवहार की ज़रूरत हो।
Warning: Adding getters and setters for every property "just in case" adds unnecessary indirection and complexity for properties that never actually need custom behavior.

उदाहरण: When to Use Getters/Setters vs Plain Properties

javascript
// Declare the constant `point`, set to `{ x: 5 }`
// Declare the constant `point`, set to `{ x: 5 }`
const point = { x: 5 };
// Declare the constant `circle`, set to `{ radius: 5, get area() { return Math.PI * this.radius ** 2; } }`
// Declare the constant `circle`, set to `{ radius: 5, get area() { return Math.PI * this.radius ** 2; } }`
const circle = { radius: 5, get area() { return Math.PI * this.radius ** 2; } };
// Print `point.x, circle.area` to the console
// Print `point.x, circle.area` to the console
console.log(point.x, circle.area);
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी getter और उसकी backing storage property का same नाम रखना, जिससे infinite recursion होता है जब getter उस property को पढ़ने की कोशिश करता है जिसे वह खुद define कर रहा है।
  2. सिर्फ एक getter define करना (कोई setter नहीं) और फिर उस property को assignment की कोशिश चुपचाप कुछ न करने (या strict mode में throw करने) पर confused होना।
  3. ऐसी simple properties के लिए getters/setters का overuse करना जिन्हें किसी computed या validated behavior की ज़रूरत नहीं, अनावश्यक complexity जोड़ते हुए।
चैप्टर सारांश
  • get propertyName() { } एक getter define करता है, जो property पढ़े जाने पर automatically invoke होता है।
  • set propertyName(value) { } एक setter define करता है, जो property को कोई नई value assign होने पर automatically invoke होता है।
  • एक common pattern getter/setter को खुद में recurse होने से बचाने के लिए एक अलग-नाम वाली backing property (जैसे _name) इस्तेमाल करता है।
ब्राउज़र सपोर्ट

Getter और setter syntax को ES5 से हर modern browser में support मिला है।

🔒

Chapter Quiz — Complete all 10 topics to unlock

0/10 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.