typescript 三種類修飾符
阿新 • • 發佈:2020-12-15
技術標籤:typescripttypescriptpublicprivateprotected類修飾符
三種修飾符以及區別 private public protected
class Animals {
// 公有屬性 public 在class內部或者外部或者子類都可訪問,不加修飾符時,預設為 public
name: string;
age: number;
/** 私有屬性animalsMotherId,只能在class內部訪問,在外部或者子類中都不能訪問 */
private animalsMotherId: number = 1;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
getName(): string {
return this.name;
}
/** 保護屬性 只有class內部和子類可以使用,在外部無法使用 */
protected setName(newName: string): void {
this.name = newName;
console.log(this.name);
}
setMotherid(newMotherId: number): void {
/** 私有屬性 class內部測試 可以正常使用 */
this.animalsMotherId = newMotherId;
}
}
let dog = new Animals('小汪', 2);
// 私有屬性外部測試 在瀏覽器程式碼能夠正常執行,(因為轉為了es5),但編譯器會提示報錯。
// console.log(dog.animalsMotherId)
// 公有屬性外部測試 在class外部可以正常使用
console.log(dog.getName())
// 保護屬性外部測試 在瀏覽器程式碼能夠正常執行,(因為轉為了es5),但編譯器會提示報錯
// dog.setName('小旺');
//子類Cat繼承父類Animals
class Cat extends Animals {
food: string | undefined;
constructor(name: string, age: number, food?: string) {
super(name, age);
this.food = food;
}
eat() {
if (this.food) {
console.log(`${this.name}愛吃${this.food}`);
} else {
throw new Error('未知食物');
}
}
replaceName(newName: string) {
/** 保護屬性子類中測試 在子類中正常使用 */
this.setName(newName);
/** 公有屬性子類中測試 在子類可以正常使用 */
console.log(this.name);
}
getMotherId() {
/** 私有屬性子類中測試 瀏覽器轉為es5後正常列印 但編譯器會報錯*/
console.log(this.animalsMotherId);
throw new Error('父類私有屬性,子類無法訪問');
}
}
let cat1 = new Cat('小喵', 2, '魚');
console.log(cat1.name, cat1.age);
cat1.replaceName('小花喵');