typescript中private、public、protected修飾符


1、默認為public

2、當成員被標記為private時,它就不能在聲明它的類的外部訪問,比如:

class Animal {
  private name: string;

  constructor(theName: string) {
    this.name = theName;
  }
}

let a = new Animal('Cat').name; //錯誤,‘name’是私有的

3、protected和private類似,但是,protected成員在派生類中可以訪問

class Animal {
  protected name: string;

  constructor(theName: string) {
    this.name = theName;
  }
}

class Rhino extends Animal {
     constructor() {
          super('Rhino');
    }         
    getName() {
        console.log(this.name) //此處的name就是Animal類中的name
    }
}    

4、構造函數也可以被標記為protected。這意味着這個類不能再包含它的類外被實例化,但是能被繼承,也就是可以在派生類中被super執行

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

//Rhino能夠繼承Animal
class Rhino extends Person {
    private food: string;
    constructor(name: string, food: string) {
       super(name);
       this.food = food;    

    }    
     getFood() {
        return `${this.name} love this ${this.food}`
     }
}

let rhino = new Rhino('zhao', 'banana');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM