Class के Basics
In this page:
class ClassName {
property: type;
method(): returnType {
// body
}
}
एक Class बनाना
एक class class keyword से declare की जाती है और इसमें data store करने के लिए properties और behavior के लिए methods हो सकते हैं, TypeScript को उस class के instances पर shape और available operations दोनों describe करने के लिए एक single जगह देते हुए।
उदाहरण: Creating a Class
class Person {
name: string = "";
greet() {
console.log(`Hello, ${this.name}`);
}
}
const p = new Person();
p.name = "Amara";
p.greet();
Class में Properties
Properties एक object द्वारा stored data represent करती हैं, और TypeScript आपको class body में सीधे हर property का type specify करने देता है, इसलिए किसी incompatible value को assign करने की कोई भी कोशिश runtime पर नहीं बल्कि compile time पर पकड़ी जाती है।
उदाहरण: Properties in a Class
class Product {
name: string;
price: number;
constructor(name: string, price: number) {
this.name = name;
this.price = price;
}
}
const item = new Product("Pen", 2);
console.log(item.name, item.price);
Class में Methods
Methods एक class के अंदर defined functions हैं जो this के through current object की properties access कर सकते हैं, behavior को उस data से जुड़ा रखते हुए जिस पर यह operate करता है बजाय free-standing functions के रूप में scattered होने के।
उदाहरण: Methods in a Class
class Counter {
count: number = 0;
increment() {
this.count++;
}
}
const c = new Counter();
c.increment();
c.increment();
console.log(c.count);
Multiple Objects बनाना
एक class का उपयोग कई independent objects बनाने के लिए किया जा सकता है, हर एक के पास अपनी instance properties होती हैं; एक object का data बदलना उसी class से बनाए किसी दूसरे object को कभी affect नहीं करता।
उदाहरण: Creating Multiple Objects
class Person {
constructor(public name: string) {}
}
const a = new Person("Zara");
const b = new Person("Leo");
console.log(a.name, b.name);
Class और Object का Relationship
एक class describe करती है कि एक object में क्या होना चाहिए और उसे क्या करना चाहिए, जबकि एक object उस description से बना एक actual instance है — वही relationship जो एक blueprint का एक building से होता है, जहां एक blueprint कई अलग-अलग buildings produce कर सकता है।
उदाहरण: Class and Object Relationship
class Car {
constructor(public model: string) {}
}
const myCar = new Car("Sedan"); // an object built from the Car blueprint
console.log(myCar.model);
name: string;को बिना किसी initializer या constructor assignment के declare करना, जोstrictPropertyInitializationके under error देता है क्योंकि property undefined हो सकती है।greet()को अकेले call करना बजायp.greet()के, या इसे एक callback के रूप में pass करना, इसलिएthisखो जाता है औरthis.namefail होता है।const p = Person();मेंnewभूल जाना, जब एक class को एक normal function जैसा call नहीं किया जा सकता।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: