Constructor की जानकारी
In this page:
class ClassName {
property: type;
constructor(param: type) {
this.property = param;
}
}
एक Constructor Define करना
एक constructor एक class के अंदर constructor keyword उपयोग करके लिखा जाता है, और इसके parameters का उपयोग new call होते ही object की initial state set up करने के लिए किया जा सकता है, इसलिए एक object कभी एक unfinished form में मौजूद नहीं होता।
उदाहरण: Defining a Constructor
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
console.log(new Person("Dev").name);
Multiple Constructor Parameters
एक constructor एक साथ कई properties initialize करने के लिए multiple parameters receive कर सकता है, और हर parameter का type उसी तरह check होता है जैसे एक regular function parameter का type होता।
उदाहरण: Multiple Constructor Parameters
class User {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const u = new User("Nina", 25);
console.log(u.name, u.age);
Constructor Defaults
Constructor parameters के default values हो सकते हैं, इसलिए जब caller उस parameter के लिए कोई value न दे, TypeScript property को undefined छोड़ने के बजाय specified default पर fall back करता है।
उदाहरण: Constructor Defaults
class Settings {
theme: string;
constructor(theme: string = "light") {
this.theme = theme;
}
}
console.log(new Settings().theme);
Parameter Properties
TypeScript parameter properties support करता है, जो constructor parameters को सिर्फ उनके आगे public या private जैसा एक access modifier जोड़कर अपने आप class properties बनने देती हैं, property को अलग से declare और assign करने की ज़रूरत हटाते हुए।
उदाहरण: Parameter Properties
class Point {
constructor(public x: number, public y: number) {}
}
const p = new Point(3, 4);
console.log(p.x, p.y);
Constructor Initialization
Constructors मायने रखते हैं क्योंकि एक object को एक valid और meaningful state में शुरू होना चाहिए; required data को पहले से initialize करना उन bugs से बचता है जो एक half-constructed object के against methods run होने से आते हैं।
उदाहरण: Constructor Initialization
class Account {
balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance; // valid state from the start
}
}
console.log(new Account(100).balance);
- body में
this.भूल जाना, जैसेname = name;, जो सिर्फ parameter को खुद assign करता है और property को unset छोड़ देता है। - एक property को
name: string;से declare करना लेकिन constructor में कभी assign न करना, जो strict property initialization fail करता है। - same class में एक से ज़्यादा constructor body define करना, जब TypeScript सिर्फ एक implementation allow करता है (extra वाले सिर्फ overload signatures हो सकते हैं)।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: