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'.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.