温馨提示:
以下内容为作者学习过程中,询问gpt4总结出来的,不保证百分之百正确。只供本人学习使用,各位读者有不同见解可以提出,但是不要喷我,我会生气!
修饰符
有修饰符
class MyComponent {
constructor(private catsService: CatsService) {}
}
无修饰符
class MyComponent {
constructor(catsService: CatsService) {}
}
没有任何访问修饰符,catsService 只是构造函数的一个参数,并不会自动成为类的属性。如果你想在类的其他方法中使用这个 CatsService 实例,你必须手动声明一个属性并在构造函数中赋值:
class MyComponent {
catsService: CatsService;
constructor(catsService: CatsService) {
this.catsService = catsService;
}
}
总结
- 有修饰符会自动成为类的属性
- 无修饰符不会自动成为类的属性,需要手动声明一个属性并在构造函数中赋值
public、protected 和 private 详解
public(公共)
public成员可以在任何地方被访问,不受限制。- 除非另外指定,类的成员默认是
public。 - 这意味着,如果你声明一个 public 成员,它可以被类的实例访问,也可以在类的外部被访问。
class MyClass {
public myPublicProperty: string;
constructor() {
this.myPublicProperty = 'Accessible from anywhere';
}
}
const instance = new MyClass();
console.log(instance.myPublicProperty); // 正常工作
protected(受保护)
protected成员只能在声明它们的类及其派生类(子类)内部被访问。- 它们对类的外部是不可见的,但是对于任何继承自该类的子类来说是可见的。
class MyClass {
protected myProtectedProperty: string;
constructor() {
this.myProtectedProperty = 'Accessible within the class and its subclasses';
}
}
class DerivedClass extends MyClass {
useProtectedProperty() {
console.log(this.myProtectedProperty); // 可以访问 protected 成员
}
}
const instance = new DerivedClass();
instance.useProtectedProperty(); // 正常工作
// console.log(instance.myProtectedProperty); // 错误:'myProtectedProperty' 受保护,只能在 'MyClass' 及其子类中访问
private(私有)
private成员只能在其声明的类内部访问。- 它们对于类的外部和子类都是不可见的。
class MyClass {
private myPrivateProperty: string;
constructor() {
this.myPrivateProperty = 'Accessible only within the class';
}
}
class DerivedClass extends MyClass {
usePrivateProperty() {
// console.log(this.myPrivateProperty); // 错误:'myPrivateProperty' 是私有的,只能在 'MyClass' 中访问
}
}
const instance = new MyClass();
// console.log(instance.myPrivateProperty); // 错误:'myPrivateProperty' 是私有的,只能在 'MyClass' 中访问