官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 梅州市| 南涧| 彭阳县| 衡东县| 桐梓县| 西畴县| 鄂伦春自治旗| 永胜县| 尼玛县| 蓬安县| 象州县| 佳木斯市| 大田县| 景宁| 邵东县| 石泉县| 睢宁县| 天峨县| 江源县| 松滋市| 容城县| 贞丰县| 东城区| 上饶县| 石门县| 安顺市| 阿图什市| 杭锦旗| 南昌县| 龙门县| 长治市| 绩溪县| 苏州市| 天长市| 武义县| 河南省| 栖霞市| 来凤县| 花垣县| 泰和县| 台中县|