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");
greeting
is a class property.- The
constructor
initializes the object with amessage
that gets assigned to thegreeting
property. greet
is a method that returns a greeting message using thegreeting
property.
Key Points:
- Class Definition: A class is defined using the
class
keyword, followed by its name (Greeter
). - Constructor: The
constructor
method 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 theGreeter
class, passing"world"
to the constructor.