美文网首页
class constructor中的public和privat

class constructor中的public和privat

作者: 陌小亓 | 来源:发表于2023-02-14 09:44 被阅读0次

    在构造函数的参数上使用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

    相关文章

      网友评论

          本文标题:class constructor中的public和privat

          本文链接:https://www.haomeiwen.com/subject/iicekdtx.html