
上QQ阅读APP看书,第一时间看更新
Private and public modifiers
In TypeScript, all members in a class are public by default. We have to add the private keyword explicitly to control the visibility of the members, and this useful feature is not available in JavaScript:
class SimpleCalculator { private x: number; private y: number; z: number; constructor(x: number, y: number) { this.x = x; this.y = y; } addition() { this.z = this.x + this.y; } subtraction() { this.z = this.x - this.y; } } class ComplexCalculator { z: number; constructor(private x: number, private y: number) { } multiplication() { this.z = this.x * this.y; } division() { this.z = this.x / this.y; } }
Note that in the SimpleCalculator class, we defined x and y as private properties, which will not be visible outside the class. In ComplexCalculator, we defined x and y using parameter properties. These Parameter properties will enable us to create and initialize a member in one statement. Here, x and y are created and initialized in the constructor itself without writing any further statements inside it.