- 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.
推薦閱讀
- 手機安全和可信應用開發指南:TrustZone與OP-TEE技術詳解
- PHP動態網站程序設計
- 從零開始構建企業級RAG系統
- Manga Studio Ex 5 Cookbook
- Raspberry Pi Networking Cookbook(Second Edition)
- VMware vSphere 6.7虛擬化架構實戰指南
- Java:Data Science Made Easy
- INSTANT CakePHP Starter
- Redis Essentials
- 青少年學Python(第1冊)
- ANSYS Fluent 二次開發指南
- jQuery Mobile移動應用開發實戰(第3版)
- Raspberry Pi Robotic Projects(Third Edition)
- Go語言底層原理剖析
- 網絡數據采集技術:Java網絡爬蟲實戰