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

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:

  1. 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;
}
}
  1. 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.

主站蜘蛛池模板: 丰城市| 柳林县| 铁岭市| 大城县| 佛山市| 车致| 抚顺市| 隆安县| 高邑县| 亳州市| 五指山市| 长春市| 张家港市| 海口市| 贞丰县| 延长县| 元朗区| 英吉沙县| 朔州市| 囊谦县| 贞丰县| 田东县| 汨罗市| 宁海县| 耿马| 邯郸市| 织金县| 龙陵县| 玛沁县| 彭泽县| 太保市| 济南市| 共和县| 无棣县| 白河县| 建瓯市| 云阳县| 准格尔旗| 浦县| 保亭| 宿迁市|