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

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.

主站蜘蛛池模板: 绥棱县| 巍山| 许昌县| 莲花县| 正镶白旗| 南召县| 和田县| 介休市| 合川市| 嫩江县| 泰安市| 庆城县| 凌海市| 金乡县| 洪雅县| 大方县| 木里| 固镇县| 休宁县| 西乌珠穆沁旗| 乌兰县| 策勒县| 三台县| 宁明县| 宿迁市| 朝阳区| 寻甸| 铜梁县| 武义县| 大港区| 那曲县| 丹江口市| 石景山区| 北海市| 平泉县| 乌拉特前旗| 裕民县| 中牟县| 清河县| 柘城县| 肃南|