Let's first see the C# class then we will convert it into TypeScript:
public class Car {
private int _x;
private int _y;
public Car(int x, int y)
{
this._x = x;
this._y = y;
}
}
Means _x
and _y
cannot be accessed from out of the class but can be assigned only through the constructor, if you want to write the same code in TypeScript it will be:
class Car {
constructor(private _x: number, private _y: number) {}
}
If you have worked with TypeScript, you can notice we use this
keyword to access these variables.
If it is only the parameter then what is the meaning of using this._x
OR this._y
out of constructor in the class, because it creates member variables as well.
Here is the JavaScript code generated from above TypeScript code:
var Car = (function () {
function Car(_x, _y) {
this._x = _x;
this._y = _y;
}
return Car;
})();
this._x
and this._y
are moved inside another function, which means Car
object cannot access it but you can initiate and assign the new Car(10, 20)
.