A class is a blueprint for creating objects, providing initial values for state (properties) and functionality (methods).
Example 1: Defining a Class
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");greetingis a class property.- The
constructorinitializes the object with amessagethat gets assigned to thegreetingproperty. greetis a method that returns a greeting message using thegreetingproperty.
Key Points:
- Class Definition: A class is defined using the
classkeyword, followed by its name (Greeter). - Constructor: The
constructormethod is a special method used to initialize new objects. It is called when creating an instance usingnew. - Methods: The class can have methods like
greet()that define the behavior of the class. - Instance Creation: The
new Greeter("world")creates a new instance of theGreeterclass, passing"world"to the constructor.