class constructor中的public和private

在构造函数的参数上使用public等同于创建了同名的成员变量

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

let user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);

输出Hello, Jane User

当成员被标记成private时,它就不能在声明它的类的外部访问

我们不能在Person类外使用name,但是我们仍然可以通过Employee类的示例方法访问,因为Employee是由Person派生而来构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。

class Person{
  protected name: string;
  constructor(name: string){
    this.name = name;
  }
}

class Employee extends Person{
  private department: string;
  
  constructor(name: string, department: string){
    super(name)
    this.department = department;
  }
  
  public getElevatorPitch() {
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch()); //Hello, my name is Howard and I work
console.log(howard.department);  // Sales 错误
console.log(howard.name);  // Howard 错误

safari浏览器可以正常打印,但是代码会提示错误

class TestClass {
  constructor(name: string, private address: string, public city){
  
   testMethod(){
     console.log(this.name)// Compiler error: property 'name' does not exist on type 'TestClass'.
     console.log(this.address);
     console.log(this.city);
   }
  }
}

const testClass = new TestClass('Johnson', '8 gaoke road', 'NanNing');
testClass.testMethod();

console.log(testClass.name); // Compiler error: property 'name' does not exist on type 'TestClass'.
console.log(testClass.address); // Compiler error: 'address' is private and only accessible within class 'TestClass'.
console.log(testClass.city) // NanNing

版权声明:本文为CSDN博主「·尘埃」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_54163765/article/details/117356187

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容