Understanding protected
The protected
modifier acts much like the private
modifier with the exception that members declared protected
can also be accessed by instances of deriving classes. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Person { protected name: string; constructor(name: string) { this .name = name; } } class Employee extends Person { private department: string; constructor(name: string, department: string) { super (name); this .department = department; } public getElevatorPitch() { return `Hello, my name is ${ this .name} and I work in ${ this .department}.`; } } let howard = new Employee( "Howard" , "Sales" ); console.log(howard.getElevatorPitch()); console.log(howard.name); // error |
Notice that while we can’t use name
from outside of Person
, we can still use it from within an instance method of Employee
because Employee
derives from Person
.
A constructor may also be marked protected
. This means that the class cannot be instantiated outside of its containing class, but can be extended. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Person { protected name: string; protected constructor(theName: string) { this .name = theName; } } // Employee can extend Person class Employee extends Person { private department: string; constructor(name: string, department: string) { super (name); this .department = department; } public getElevatorPitch() { return `Hello, my name is ${ this .name} and I work in ${ this .department}.`; } } let howard = new Employee( "Howard" , "Sales" ); let john = new Person( "John" ); // Error: The 'Person' constructor is protected |
Please login to continue.