在 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>Shared properties in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to the view properties of student1 and student2 objects</h3>
<script>
   let resEle = document.querySelector(".result");
   function Student(name, age) {
      this.name = name;
      this.age = age;
   }
   Student.prototype.school = "St Marks School";
   let student1 = new Student("Rohan", 17);
   let student2 = new Student("Shawn", 16);
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = `${student1.name} age ${student1.age} : school
      :${student1.school} <br>`;
      resEle.innerHTML += `${student2.name} age ${student2.age} : school
      :${student2.school}`;
   });
</script>
</body>
</html>

輸出

點選“單擊此處”按鈕 -

更新於:20-Jul-2020

319 次瀏覽

開啟你的職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.