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>輸出

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

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP