- Learn React with TypeScript 3
- Carl Rippon
- 232字
- 2021-06-10 19:16:36
Property setters and getters
Our classes so far have had simple property declarations. However, for more complex scenarios, we can implement a property with a getter and a setter. When implementing getters and setters, generally, you'll need a private property to hold the property value:
- getter is a function with the property name and the get keyword at the beginning and no parameters. Generally, this will return the value of the associated private property.
- setter is a function with the same name with the set keyword at the beginning and a single parameter for the value. This will set the value of the associated private property.
- The private property is commonly named the same as the getter and setter with an underscore in front.
Let's take a look at an example:
- Let's create getters and setters for the unitPrice property in our Product class. The setter ensures the value is not less than 0. The getter ensures null or undefined is never returned:
class Product {
name: string;
private _unitPrice: number;
get unitPrice(): number {
return this._unitPrice || 0;
}
set unitPrice(value: number) {
if (value < 0) {
value = 0;
}
this._unitPrice = value;
}
}
- Let's consume the Product class and try this out:
const table = new Product();
table.name = "Table";
console.log(table.unitPrice);
table.unitPrice = -10;
console.log(table.unitPrice);
If we run this, we should see two 0's in the console.
推薦閱讀
- 極簡算法史:從數學到機器的故事
- Docker技術入門與實戰(第3版)
- 劍指Offer(專項突破版):數據結構與算法名企面試題精講
- Learning SAP Analytics Cloud
- Mastering Apache Spark 2.x(Second Edition)
- ArcGIS By Example
- Hands-On Natural Language Processing with Python
- Java編程的邏輯
- AIRIOT物聯網平臺開發框架應用與實戰
- HTML5 APP開發從入門到精通(微課精編版)
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- Practical GIS
- 超好玩的Scratch 3.5少兒編程
- 零基礎學Java第2版