在TypeScript中,访问修饰符是一种用于限制类成员(属性和方法)访问权限的标识符。它可以帮助我们控制类成员的可见性和可访问性。
public是默认的访问修饰符。使用public修饰符可以使类的成员在类内部和外部均可访问。
class Person {
public name: string;
public age: number;
public constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public sayHello(): void {
console.log(`Hello, my name is ${this.name}, I'm ${this.age} years old.`);
}
}
let person = new Person('John', 25);
console.log(person.name);
console.log(person.age);
person.sayHello();
在上面的代码中,name和age都使用了public修饰符,所以它们可以在Person类内部和外部访问。sayHello方法也使用了public修饰符,可以被外部调用。
private修饰符用于限制类成员只能在类内部访问。外部无法访问private修饰的成员。
class Person {
private name: string;
private age: number;
public constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
private sayHello(): void {
console.log(`Hello, my name is ${this.name}, I'm ${this.age} years old.`);
}
}
let person = new Person('John', 25);
console.log(person.name); // 编译错误,无法访问
console.log(person.age); // 编译错误,无法访问
person.sayHello(); // 编译错误,无法访问
在上面的代码中,name、age和sayHello方法都使用了private修饰符,所以它们只能在Person类内部访问。外部无法访问。
protected修饰符用于限制类成员只能在类内部和子类中访问。外部无法访问protected修饰的成员。
class Person {
protected name: string;
protected age: number;
public constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
class Student extends Person {
public school: string;
public constructor(name: string, age: number, school: string) {
super(name, age);
this.school = school;
}
public displayInfo(): void {
console.log(`Name: ${this.name}, Age: ${this.age}, School: ${this.school}`);
}
}
let student = new Student('John', 25, 'ABC School');
console.log(student.name); // 编译错误,无法访问
console.log(student.age); // 编译错误,无法访问
student.displayInfo();
在上面的代码中,name和age都使用了protected修饰符,所以它们只能在Person类内部和子类中访问。外部无法访问。displayInfo方法没有使用修饰符,默认是public修饰符,可以被外部调用。
通过本文的介绍,相信你已经了解了TypeScript中访问修饰符的使用方法。在实际开发中,合理使用访问修饰符可以提高代码的安全性和可维护性。
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com
