- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 174字
- 2021-07-15 17:05:32
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.
推薦閱讀
- Vue.js 3.x快速入門
- 自然語言處理實戰:預訓練模型應用及其產品化
- Angular UI Development with PrimeNG
- Learning Selenium Testing Tools with Python
- Python機器學習編程與實戰
- Building a Quadcopter with Arduino
- 算法訓練營:提高篇(全彩版)
- Visual Basic程序設計
- Android應用開發實戰
- Distributed Computing in Java 9
- Learning Nessus for Penetration Testing
- 大數據時代的企業升級之道(全3冊)
- Mastering Embedded Linux Programming
- SQL Server實例教程(2008版)
- Web前端測試與集成:Jasmine/Selenium/Protractor/Jenkins的最佳實踐