- Published on
Access Modifiers
- Authors
- Name
- Khánh
Access modifier
- public: Allows access to methods and variables from outside the class.
- private: Restricts access to only within the class where it is defined.
- protected: Provides access within the class it is defined and its subclasses (derived classes).
- get: Defines a getter method for private properties.
- set: Defines a setter method for private properties.
=> If no access modifier is specified, the default is public.
Example
class Car {
public start:string;
private sheet: number;
protected shape: string;
constructor(str: string){
this.start = str;
this.sheet = 5;
this.shape = "circle";
}
public getSheet(){
return this.sheet;
}
}
class Car7Sheet extends Car {
constructor(){
super("7 sheet start");
}
public getShape(){
return this.shape;
}
}
const svCar = new Car7Sheet();
console.log(svCar.getShape());
// "circle"
console.log(svCar.start);
// "7 sheet start"
Example of getter and setter
class Person {
private _age: number;
private _firstName: string;
private _lastName: string;
constructor(age: number, firstName: string, lastName: string){
this._age = age;
this._firstName = firstName;
this._lastName = lastName;
}
public get age() {
return this._age;
}
public set age(theAge: number) {
if (theAge <= 0 || theAge >= 200) {
throw new Error('The age is invalid');
}
this._age = theAge;
}
public getFullName(): string {
return `${this._firstName} ${this._lastName}`;
}
}
const person = new Person(24,"dang","khanh");
person.age = 12;
console.log(person.age);
// 12
person.age = -1;
// "Executed JavaScript Failed:"
// The age is invalid
console.log(person.age)