Static Members की जानकारी
In this page:
class ClassName {
static property: type = value;
static method(): returnType {
// body
}
}
ClassName.method();
Static Properties
एक static property class खुद द्वारा shared होती है और इसे एक instance के बजाय class name उपयोग करके access किया जाता है, इसलिए इसे पढ़ने या update करने के लिए सिर्फ एक object बनाने की ज़रूरत नहीं है।
उदाहरण: Static Properties
class Counter {
static count: number = 0;
}
Counter.count++;
console.log(Counter.count);
Static Methods
Static methods class name उपयोग करके call किए जाते हैं और उपयोगी हैं जब एक operation किसी particular instance के data पर depend न करे, जैसे एक helper जो उस class के objects बनाता या validate करता है।
उदाहरण: Static Methods
class MathUtils {
static square(n: number): number {
return n * n;
}
}
console.log(MathUtils.square(5));
Static और Instance Members
Instance members individual objects के होते हैं, जबकि static members पूरी class के होते हैं, इसलिए एक static property बदलना पूरे program में इसके हर reference को एक साथ affect करता है।
उदाहरण: Static and Instance Members
class Counter {
static total: number = 0;
constructor() {
Counter.total++;
}
}
new Counter();
new Counter();
console.log(Counter.total);
Static Members और this
Static methods किसी single instance के बजाय class के context में operate करते हैं, इसलिए वे instance properties refer करने के लिए this उपयोग नहीं कर सकते — एक static method के अंदर refer करने के लिए बस कोई instance ही नहीं होता।
उदाहरण: Static Members and this
class Config {
static appName: string = "MyApp";
static getName(): string {
return Config.appName; // uses class name, not "this"
}
}
console.log(Config.getName());
Static Members के Common उपयोग
Static members आमतौर पर constants, counters, factory methods, और utility functions के लिए उपयोग होते हैं जो logically एक class के साथ belong करते हैं लेकिन अपना काम करने के लिए per-object state की ज़रूरत नहीं रखते।
उदाहरण: Common Uses of Static Members
class IdGenerator {
private static nextId: number = 1;
static generate(): number {
return IdGenerator.nextId++;
}
}
console.log(IdGenerator.generate(), IdGenerator.generate());
- एक static member को एक instance के through access करना, जैसे
new Counter().count, जब इसेCounter.countके रूप में reach किया जाना चाहिए। - एक static method के अंदर
this.someInstancePropertyउपयोग करना, जब कोई instance ही नहीं होता इसलिए यह instance members नहीं देख सकता। - यह उम्मीद करना कि हर object के पास एक static property की अपनी copy है, जब यह value पूरी class द्वारा shared होती है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: