- Mastering TypeScript 3
- Nathan Rozentals
- 434字
- 2021-07-02 12:42:52
Class property accessors
ECMAScript 5 introduces the concept of property accessors. An accessor is simply a function that is called when a user of our class either sets a property, or retrieves a property. This means that we can detect when users of our class are either getting or setting a property, and can be used as a trigger mechanism for other logic. To use accessors, we create a pair of get and set functions (with the same function name) in order to access an internal property. This concept is best understood with some code samples, as follows:
class ClassWithAccessors { private _id : number | undefined; get id() { console.log(`inside get id()`); return <number>this._id; } set id(value:number) { console.log(`inside set id()`); this._id = value; } }
This class has a private _id property and two functions, both called id. The first of these functions is prefixed by the get keyword. This get function is called when a user of our class retrieves, or reads, the property. In our sample, the get function logs a debug message to the console, and then simply returns the value of the internal _id property.
The second of these functions is prefixed with the set keyword and accepts a value parameter. This set function will be called when a user of our class assigns a value, or sets the property. In our sample, we simply log a message to the console, and then set the internal _id property. Note that the internal _id property is private, and as such cannot be accessed outside of the class itself.
We can now use this class, as follows:
var classWithAccessors = new ClassWithAccessors(); classWithAccessors.id = 2; console.log(`id property is set to ${classWithAccessors.id}`);
Here, we have created an instance of this class, and named it classWithAccessors. Note how we are not using the two separate functions named get and set. We are simply using them as a single id property. When we assign a value to this property, the ECMAScript 5 runtime will call the set id(value) function, and when we retrieve this property, the runtime will call the get id() function. The output of this code is as follows:
inside set id() inside get id() id property is set to 2
Using getter and setter functions allows us to hook in to class properties, and execute code when these class properties are accessed.