Symbol का Type
In this page:
const sym: symbol = Symbol("description");
Creating Symbols
Symbol() call करना एक unique symbol value बनाता है — हर single call genuinely एक distinct symbol produce करती है, भले ही आप दो अलग calls को exact same description string pass करें।
उदाहरण: Creating Symbols
const a = Symbol("id");
const b = Symbol("id");
console.log(a === b);
Symbols as Object Keys
एक symbol को एक object पर एक computed property key के रूप में उपयोग किया जा सकता है, और उस property को फिर सिर्फ exact same symbol reference उपयोग करके ही access किया जा सकता है — कोई और symbol या string उस तक नहीं पहुंचेगा।
उदाहरण: Symbols as Object Keys
const idKey = Symbol("id");
const user = { name: "Ravi", [idKey]: 42 };
console.log(user[idKey]);
Symbol Properties and Enumeration
Symbol-keyed properties deliberately Object.keys और normal for...in enumeration से invisible हैं, हालांकि Object.getOwnPropertySymbols किसी object की symbol keys retrieve कर सकता है अगर आप specifically उन्हें ढूंढने जाएं।
उदाहरण: Symbol Properties and Enumeration
const idKey = Symbol("id");
const user = { name: "Ravi", [idKey]: 42 };
console.log(Object.keys(user));
console.log(Object.getOwnPropertySymbols(user));
Symbol Registry
Symbol.for एक string से keyed global, shared registry से एक symbol बनाता या retrieve करता है — Symbol() के विपरीत, same key के साथ Symbol.for की दो calls exact same symbol return करती हैं।
उदाहरण: Symbol Registry
const a = Symbol.for("shared");
const b = Symbol.for("shared");
console.log(a === b);
Symbols in APIs
Symbols वह तरीका हैं जिससे JavaScript internally special object protocols define करता है (जैसे Symbol.iterator) और independent pieces of code को shared objects में properties जोड़ने देते हैं बिना colliding property names के किसी risk के।
उदाहरण: Symbols in APIs
class Range {
constructor(private start: number, private end: number) {}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next: () => current < end
? { value: current++, done: false }
: { value: undefined, done: true },
};
}
}
console.log([...new Range(1, 4)]);
- same description से बनाए गए दो symbols compare करना और
trueकी उम्मीद करना, जबSymbol("id") === Symbol("id")falseहै। new Symbol()उपयोग करना, जो एकTypeErrorthrow करता है क्योंकिSymbolएक constructor नहीं है।- यह उम्मीद करना कि
Object.keysयाJSON.stringifysymbol-keyed properties दिखाएंगे, जिन्हें वे skip करते हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: