JavaScript 中的訪問器屬性及自定義屬性。


訪問器屬性幫助我們在 JavaScript 中實現 getter 和 setter 函式。在獲取或設定值時會執行函式。

訪問器屬性有四個屬性−

  • get − 在讀取屬性時呼叫。它不接受任何引數。
  • set − 在設定屬性時呼叫。它只接受一個引數。
  • enumerable − 設定為 true 時允許物件可迭代。
  • configurable − 設定為 false 時,不允許刪除屬性或更改其值。

以下是訪問器屬性及其屬性的程式碼 -

示例

 線上演示

<!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>Accessor property and its attributes</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to use set and get to modify and display person object properties</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let person = {
      name: "Rohan",
      age: 22,
      occupation: "Student",
      get fullname() {
         return this.name;
      },
      set job(occupation) {
         this.occupation = occupation;
      },
   };
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      "Name = " + person.fullname + " : Occupation = " + person.occupation;
      resEle.innerHTML += "<br>After modifying occupation property <br>";
      person.occupation = "Developer";
      resEle.innerHTML += "New Occupation = " + person.occupation;
   });
</script>
</body>
</html>

輸出

單擊“單擊此處”按鈕後−

更新時間:20-7-2020

165 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.