Reputation: 1414
Am I right that public members in a TypeScript constructor are public in the class and that private members are private?
If so, what is the effective difference between public members and properties?
Assuming that the difference is that properties can act more like c# properties (that is, can have code associated with their access) why would you want to make a field public, without the protections inherent in making it a property?
Upvotes: 4
Views: 4401
Reputation: 22733
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)
.
Upvotes: 2
Reputation: 1414
private creates a field and public creates a property.
This is not like a C# property, in fact what makes it a property is just that it is public. There are no accessors.
Upvotes: 5