Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 97047b5

Browse files
Merge pull request #158 from AbubakerB/classesModifierUpdate
Add protected constructor topic
2 parents 32f5626 + 05bd50c commit 97047b5

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

pages/Classes.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,9 +189,36 @@ console.log(howard.name); // error
189189

190190
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`.
191191

192+
A constructor may also be marked `protected`.
193+
This means that the class cannot be instantiated outside of its containing class, but can be extended. For example,
194+
195+
```ts
196+
class Person {
197+
protected name: string;
198+
protected constructor(theName: string) { this.name = theName; }
199+
}
200+
201+
// Employee can extend Person
202+
class Employee extends Person {
203+
private department: string;
204+
205+
constructor(name: string, department: string) {
206+
super(name);
207+
this.department = department;
208+
}
209+
210+
public getElevatorPitch() {
211+
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
212+
}
213+
}
214+
215+
let howard = new Employee("Howard", "Sales");
216+
let john = new Person("John"); // Error: The 'Person' constructor is protected
217+
```
218+
192219
## Parameter properties
193220

194-
In our last example, we had to declare a private member `name` and a constructor parameter `theName`, and we then immediately set `name` to `theName`.
221+
In our last example, we had to declare a protected member `name` and a constructor parameter `theName` in the `Person` class, and we then immediately set `name` to `theName`.
195222
This turns out to be a very common practice.
196223
*Parameter properties* let you create and initialize a member in one place.
197224
Here's a further revision of the previous `Animal` class using a parameter property:

0 commit comments

Comments
 (0)