MMA with Ionic 3 - Tutorial Part 9 Constructors in Typescript

See Image Larger
MMA for Make Mobile Applications
In last post, we talked about Classes. I rewrite the code that we wrote in last post;
class Rectangle {
x: number;
y: number;
area() {
return this.x * this.y;
}
}
We will create new object from Rectangle class and called area function;
let rectangle = new Rectangle;
rectangle.x = 4;
rectangle.y = 5;
let areaOfRectangle = rectangle.area();
What if this point object had, if you had a properties that we had to initialize like this;
let rectangle = new Rectangle;
rectangle.x = 4;
rectangle.y = 5;
rectangle.z = 3
Is there a cleaner way? In object oriented programming languages, we have the concept called constructor. So every class can have a constructor which basically a method that is called when create new instance of that class. So let me show you how it works. In the class, I’m gonna add a method. Name of this method is constructor that reserved keyword in Typescript. That method can have parameters.
class Rectangle {
x: number;
y: number;
constructor(x: number, y: number) {
}
area() {
return this.x * this.y;
}
}
In constructor method, we can initialize this field. I’m completing the constructor method.
// ...
constructor(x: number, y: number) {
this.x = x;
this.y=y;
}
// ...
We got a compilation error here;

See Image Larger
Because when creating new Rectangle object, we need the supply the parameters. So lines that we create new rectangle object in our code;
// ...
let rectangle = new Rectangle(4, 5);
let areaOfRectangle = rectangle.area();
What is somewhere else in our program, we don’t know the initial sides’ length of rectangle? In other words, what if I wanna create a rectangle object without setting parameters? So the solution for this is to make these parameters optional. If we add question mark after variable names, we create optional parameters.
// ...
constructor(x?: number, y?: number) {
this.x = x;
this.y=y;
}
// ...
So if we delete parameters in new rectangle object, we don’t have a compilation error.

See Image Larger
This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond Please consider upvoting this comment as this project is supported only by your upvotes!
This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond