In terms of OOPs(Object Oriented Programming), a class is a blueprint which is used for creating objects. A class is a collection of objects having common properties.It contains methods,constructors,blocks,nested classes,interfaces etc. Objects are basically the entities that have some properties like an object in the real world(chair, table etc).
Syntax to declare a class:
Note: The typescript code is saved using the .ts extension.
Let’s see some typescript examples too:
The example declare a Student class which has two fields that is studCode and studName and a constructor which is special type of function which is responsible for variable or object initialization. Here it is parameterized constructor(already having the parameters). And this keyword which refers to the current instance of the class. getGrade() is a simple function which returns a string.
An object is an instance of class which contains set of key value pairs. It’s value may be scalar values or functions or even array of other objects.
Syntax of an Object looks like the code below:
An object can contain scalar value, functions and structures like arrays and tuples.
Let’s see with simple example:
For creating Instance Objects.
To create an instance of the class, use with the new keyword followed by the class name. To allocates memory for objects with the help new during runtime. Like:
In order to create an instance of an object we can do something like the code below.
Accessing Attributes and Functions:
A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation or bracket notation([”]) we access the data members of a class.
//accessing an attribute obj.field_name or obj['field_name'] //accessing a function obj.function_name()
Consider the code below: