What is the difference between Private and Protected variables in TypeScript?
What is the difference between Private and Protected variables in TypeScript?
In TypeScript, the difference between private and protected variables pertains to their accessibility within classes and their subclasses.
Private variables in TypeScript are accessible only within the class where they are declared. They cannot be accessed from outside of this class, not even from classes that inherit from this class. This strict access control is useful for encapsulating sensitive data or implementation details that should not be exposed outside of the class.
For example, if a class Person
has a private variable age
, this variable can only be accessed by methods within the Person
class. Attempting to access this variable from outside the class, or from a subclass, will result in a compilation error.
class Person {
private age: number;
constructor(age: number) {
this.age = age;
}
displayAge() {
console.log(this.age);
}
}
const person = new Person(30);
person.displayAge(); // Works
console.log(person.age); // Error: 'age' is private and only accessible within class 'Person'.
Protected variables, on the other hand, are similar to private variables but with a less restrictive level of access control. Protected variables are accessible within the class in which they are declared as well as by instances of classes that inherit from this class.
This means that if a class Employee
extends the Person
class, it can access any protected variables declared in Person
.
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
constructor(name: string) {
...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào