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

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.

主站蜘蛛池模板: 江都市| 岢岚县| 湖口县| 东乌珠穆沁旗| 镇康县| 诏安县| 叙永县| 庆元县| 察哈| 江城| 精河县| 德安县| 泸西县| 天台县| 治县。| 平乐县| 长岛县| 曲周县| 贵溪市| 怀化市| 防城港市| 抚远县| 临桂县| 永年县| 武强县| 福清市| 吴川市| 武定县| 当雄县| 宁化县| 梓潼县| 忻城县| 常宁市| 华容县| 灵川县| 沙洋县| 常德市| 徐州市| 鹿泉市| 通化县| 灵寿县|