- Mastering TypeScript 3
- Nathan Rozentals
- 279字
- 2021-07-02 12:42:51
Class properties
A class is the definition of an object, and as such, includes the data that it can hold, in the form of class properties. These properties can be accessed by users of this class, if we so wish, or can be marked as not accessible. Regardless of what their accessibility rules are, code within the class will need to access these class properties. In order to access the properties of a class from within the class itself, we need to use the this keyword. As an example, let's update our SimpleClass definition, and print out the value of the id property within the print function, as follows:
class SimpleClass { id: number | undefined; print() : void { console.log(`SimpleClass has id : ${this.id}`); } }
Here, we have modified the print function to reference the id property of the class instance within the template string, ${this.id}. Whenever we are inside a class instance, we must use the this keyword in order to access any property or function available on the class definition. The this keyword, therefore, indicates to the compiler that we are referencing a class property, or class function.
Once we have created an instance of the class, we can set the id property, and then call the updated print function, as follows:
let mySimpleClass = new SimpleClass(); mySimpleClass.id = 1001; mySimpleClass.print();
The output of this code will be as follows:
SimpleClass has id : 1001
Here, we have set the id property of the mySimpleClass variable, and have seen how the print function can access the id property from within the definition of the class itself in order to print the value to the console.