Let's start by examining the C# class before converting it to TypeScript:
public class Car {
private int _x;
private int _y;
public Car(int x, int y)
{
this._x = x;
this._y = y;
}
}
This means that _x
and _y
can only be accessed within the class and can only be assigned values through the constructor. When translating the same code to TypeScript, it looks like this:
class Car {
constructor(private _x: number, private _y: number) {}
}
If you are familiar with TypeScript, you might have noticed that we use the keyword this
to access these variables.
But what is the purpose of using this._x
or this._y
outside of the constructor in the class if they are only parameters? It actually creates member variables as well.
Now, let's see the JavaScript code that is generated from the TypeScript code above:
var Car = (function () {
function Car(_x, _y) {
this._x = _x;
this._y = _y;
}
return Car;
})();
In this JavaScript version, this._x
and this._y
are encapsulated within another function, which means that the Car
object cannot directly access them. However, you can still initialize and assign values like new Car(10, 20)
.