TypeScript 中的私有、公有和受保護訪問修飾符


訪問修飾符至關重要,因為它們允許我們強制執行封裝並定義類成員可訪問性的邊界。使用訪問修飾符,我們可以限制對某些成員的訪問,確保它們僅在類本身內可訪問。我們還可以將成員設為公共,允許它們在我們的程式碼庫中的任何地方訪問。此外,受保護的成員允許在類及其派生類中訪問。

在本教程中,我們將探討 TypeScript 中的私有、公有和受保護訪問修飾符。

語法

使用者可以按照以下語法在 TypeScript 中將訪問修飾符應用於類成員:

class ClassName {
   private propertyName: type;
   public methodName(): returnType {
      // Method body
   }
   protected anotherPropertyName: type;
}

在上述語法中:

  • private − 此訪問修飾符將成員的訪問許可權限制為其宣告所在的類。關鍵字 private 表示它。

  • public − 此訪問修飾符允許從任何地方無限制地訪問成員。如果未指定任何訪問修飾符,則為預設訪問修飾符。關鍵字 public 表示它。

  • protected − 此訪問修飾符允許在類及其派生類中訪問成員。它由關鍵字 protected 表示。

示例 1:公共訪問修飾符

在此示例中,我們建立了一個名為 Person 的類,它具有一個公共屬性 name,可以在程式碼中的任何地方訪問和修改。我們還有一個公共方法 greet(),它使用 name 屬性列印問候語。

然後,我們建立名為 Person 的 Person 類的例項。我們可以直接訪問 person 物件的 name 屬性併為其賦值。最後,我們在 person 物件上呼叫 greet() 方法,該方法輸出問候語,包括 name。使用者可以觀察輸出以檢視帶有提供的 name 的問候語。

class Person {
   public name: string = "";

   public greet(): void {
      console.log(`Hello, my name is ${this.name}!`);
   }
} 
// Creating an instance of the Person class
const person = new Person(); 

// Assigning a value to the public property
person.name = "John"; 

// Calling the public method to display the greeting
person.greet();

編譯後,它將生成以下 JavaScript 程式碼:

var Person = /** @class */ (function () {
   function Person() {
      this.name = "";
   }
   Person.prototype.greet = function () {
      console.log("Hello, my name is ".concat(this.name, "!"));
   };
   return Person;
}());
// Creating an instance of the Person class
var person = new Person();

// Assigning a value to the public property
person.name = "John";

// Calling the public method to display the greeting
person.greet();

輸出

以上程式碼將產生以下輸出:

Hello, my name is John!

示例 2:私有訪問修飾符

在此示例中,我們建立了一個名為 BankAccount 的類,它具有一個私有屬性 balance,只能在類內訪問和修改。此外,我們還有一個私有方法 calculateInterest(),它根據 balance 計算利息。

定義類後,我們建立名為 account 的 BankAccount 類的例項,初始餘額為 $1000。

但是,嘗試從類外部直接訪問私有屬性 balance 或呼叫私有方法 calculateInterest() 將導致錯誤,因為這些成員在類範圍之外是不可訪問的。

使用者可以在輸出中觀察到,嘗試訪問私有成員將導致 TypeError。

class BankAccount {
   private balance: number; 
   constructor(initialBalance: number) {
      this.balance = initialBalance;
   } 
   private calculateInterest(): number {
      const interestRate = 0.05;
      return this.balance * interestRate;
   } 
}  
// Creating an instance of the BankAccount class
const account = new BankAccount(1000); 

// Attempting to access private members
console.log(account.balance); 
console.log(account.calculateInterest()); 

編譯後,它將生成以下 JavaScript 程式碼:

var BankAccount = /** @class */ (function () {
   function BankAccount(initialBalance) {
      this.balance = initialBalance;
   }
   BankAccount.prototype.calculateInterest = function () {
      var interestRate = 0.05;
      return this.balance * interestRate;
   };
   return BankAccount;
}());
// Creating an instance of the BankAccount class
var account = new BankAccount(1000);

// Attempting to access private members
console.log(account.balance);
console.log(account.calculateInterest());

它將給出以下錯誤:

Property 'balance' is private and only accessible within class 'BankAccount'.
Property 'calculateInterest' is private and only accessible within class 'BankAccount'.

輸出

以上 JavaScript 程式碼將產生以下輸出:

1000
50

示例 3:受保護的訪問修飾符

在此示例中,我們建立了一個名為 Animal 的基類,它具有一個受保護的屬性 name,可以在類及其派生類中訪問和修改。我們還有一個受保護的方法 makeSound(),它只記錄一條訊息。

然後,我們建立一個派生類 Dog,它擴充套件了 Animal 類。Dog 類添加了一個公共方法 bark(),它利用從基類繼承的 name 屬性來輸出一條吠叫訊息。

最後,我們建立名為 dog 的 Dog 類的例項,其名稱為“Buddy”,並呼叫 bark() 方法。

輸出將顯示狗的名稱,後跟吠叫訊息。

class Animal {
   protected name: string; 
   constructor(name: string) {
      this.name = name;
   } 
   protected makeSound(): void {
      console.log("The animal makes a sound");
   }
} 
class Dog extends Animal {
   public bark(): void {
      console.log(`${this.name} barks!`);
   }
} 
// Creating an instance of the Dog class
const dog = new Dog("Buddy"); 
dog.bark();

編譯後,它將生成以下 JavaScript 程式碼:

var __extends = (this && this.__extends) || (function () {
   var extendStatics = function (d, b) {
      extendStatics = Object.setPrototypeOf ||
         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
         function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
      return extendStatics(d, b);
    };
    return function (d, b) {
      if (typeof b !== "function" && b !== null)
         throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
      extendStatics(d, b);
      function __() { this.constructor = d; }
      d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
   };
})();
var Animal = /** @class */ (function () {
   function Animal(name) {
      this.name = name;
   }
   Animal.prototype.makeSound = function () {
      console.log("The animal makes a sound");
   };
   return Animal;
}());
var Dog = /** @class */ (function (_super) {
   __extends(Dog, _super);
   function Dog() {
      return _super !== null && _super.apply(this, arguments) || this;
   }
   Dog.prototype.bark = function () {
      console.log("".concat(this.name, " barks!"));
   };
   return Dog;
}(Animal));
// Creating an instance of the Dog class
var dog = new Dog("Buddy");
dog.bark();

輸出

編譯後,以上程式碼將生成一個 JavaScript 程式碼。JavaScript 程式碼將產生以下結果:

Buddy barks!

在本教程中,我們學習了 TypeScript 中的私有、公有和受保護訪問修飾符。私有成員只能在類內訪問,公共成員可以在任何地方訪問,受保護的成員可以在類及其派生類中訪問。透過使用這些訪問修飾符,我們可以根據需要控制類成員的可見性和可訪問性。

更新於: 2023年8月21日

404 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告