除了 JavaScript 類中的建構函式之外,還有其他方法嗎?


在這篇文章中,我們將學習除了 JavaScript 類中的建構函式之外的另一種方法,並提供相應的 JavaScript 示例。

建構函式用於建立和初始化類的例項,即物件。建構函式的作用是構建一個新物件併為物件上已存在的任何屬性設定值。每個類都有一個預設建構函式。如果我們不提供自己的建構函式,則將呼叫預設建構函式。

讓我們透過本文後面提供的合適示例來更好地理解這個概念。

語法

建構函式的語法如下:

Constructor(); // No parameters
Constructor(param1); //One parameter constructor
Constructor(param1,param2,…,paramN) // N-parameter constructor.

Param1、param2、…paramN 是傳遞給建構函式的引數。

示例 1

這是一個編寫除了建構函式之外的方法的示例程式。

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Another method other than a constructor in a JavaScript class</title>
</head>
<body style="text-align: center ;">
   <p> Another method other than a constructor in a JavaScript class </p>
   <p id="method"></p>
   <script>
      class Person {
         constructor(name){
            this.name = name;
         }
         PersonName() {
            return 'The person name is : '+this.name;
         }
      }
      person_1 = new Person("Raghu");
      document.getElementById("method").innerHTML = person_1.PersonName();
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 2

這是一個說明除了建構函式之外的方法用法的示例程式。我們使用了一個名為 PersonDetails() 的使用者定義方法來進行初始化,而不是使用預設建構函式。

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Another method other than a constructor in a JavaScript class</title>
</head>
<body style="text-align: center ;">
   <p> Another method other than a constructor in a JavaScript class </p>
   <p id="method"></p>
   <script>
      class Person {
         constructor(name, EmployeeID, designation) {
            this.name = name;
            this.EmployeeID = EmployeeID;
            this.designation = designation;
         }
         PersonDetails() {
            return this.name + " has the designation : " + this.designation;
         }
      }
      person_1 = new Person("Rajesh", "10023", "Software Engineer");
      document.getElementById("method").innerHTML = person_1.PersonDetails();
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 3

在下面的示例中,屬性實際上是在一個名為“anotherMet()”的使用者給定方法中初始化的,而不是使用預設方法 constructor()。透過此方法,實際結果在輸出中執行,如所示。

<html>
<body>
   <p id="method"></p>
   <script>
      class Company {
         constructor(branch) {
            this.name = branch;
         }
         anotherMet(x) {
            return x + " is the head of " + this.name;
         }
      }
      myComp = new Company("Microsoft.");
      document.getElementById("method").innerHTML = myComp.anotherMet("Bill gates");
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

更新於: 2022-12-09

194 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告