
上QQ阅读APP看书,第一时间看更新
Accessors
We can also implement getters and setters to the properties to control accessing them from the client. We can intercept a process before setting a value to a property variable or before getting a value of the property variable:
var updateCustomerNameAllowed = true; class Customer { private _name: string; get name: string { return this._name; } set name(newName: string) { if (updateCustomerNameAllowed == true) { this._name = newName; } else { alert("Error: Updating Customer name not allowed!"); } } }
Here, the setter for the name property ensures that the customer name can be updated. Otherwise, it shows an alert message to the effect that it is not possible.