在類中函式之前的“get”關鍵字是什麼 - JavaScript?


get 關鍵字可以用作 C#、Java 和其他技術中的 getter 函式。

我們在類中設定了一個帶 get 的函式,如下所示 -

class Employee {
   constructor(name) {
   this.name = name;
   }
   get fullName() {
      return this.name;
   }
}

示例

以下程式碼顯示了 get 的示例 -

class Employee {
   constructor(name) {
      this.name = name;
   }
   get fullName() {
      return this.name;
   }
}
var employeeObject = new Employee("David Miller");
console.log(employeeObject.fullName);

要執行以上程式,你需要使用以下命令 -

node fileName.js.

此處,我的檔名是 demo299.js。

輸出

這將在控制檯上產生以下輸出 -

PS C:\Users\Amit\javascript-code> node demo299.js
David Miller

更新於: 09-11-2020

361 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.