靜態屬性 in JavaScript


靜態屬性分配給類函式本身,而不是分配給其原型屬性。無需例項化任何物件即可直接呼叫這些屬性。

以下是 JavaScript 中靜態屬性的程式碼 −

示例

 現場演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Static Properties in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the access the static property school of Student</h3>
<script>
   let resEle = document.querySelector(".result");
   function Student(name, age) {
      this.name = name;
      this.age = age;
   }
   Student.school = "St Marks Public School";
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = "Student.school = " + Student.school;
   });
</script>
</body>
</html>

輸出

在單擊“點選此處”按鈕後 −

更新日期:20-Jul-2020

112 人檢視

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.