- Learning TypeScript 2.x
- Remo H. Jansen
- 231字
- 2025-04-04 17:02:05
The protected access modifier
If we use the protected modifier, the method or property can only be accessed by the object that owns them or instances of the derived classes.
The following example declares, once more, the classes that we declared in the preceding examples, but uses the protected access modifier instead of the public modifier:
class Person { public name: string; public surname: string; protected _email: string; public constructor( name: string, surname: string, email: string ) { this._email = email; this.name = name; this.surname = surname; } public greet() { console.log("Hi!"); } } class Teacher extends Person { public teach() { console.log("Welcome to class!"); } public shareEmail() { console.log(`My email is ${this._email}`); } }
If we create an instance of both the Person and Teacher classes, we will be able to observe that the protected property, email, can be accessed from the method named shareEmail, which is declared by the derived Teacher class. However, other objects (such as the console object) cannot access the private property. This code snippet confirms that the email property can only be accessed by the instances of the Person class or derived classes, but it cannot be accessed by other objects:
const person = new Person( "Remo", "Jansen", "remo.jansen@wolksoftware.com" ); const teacher = new Teacher( "Remo", "Jansen", "remo.jansen@wolksoftware.com" ); console.log(person._email); // Error console.log(teacher._email); // Error teacher.shareEmail(); // "My email is remo.jansen@wolksoftware.com"