접근자 속성은 JavaScript에서 getter 및 setter 함수를 구현하는 데 도움이 됩니다. 값을 가져오거나 설정할 때 함수를 실행합니다.
접근자 속성에는 네 가지 속성이 있습니다. -
- 얻다 − 속성을 읽을 때 호출됩니다. 어떤 인수도 필요하지 않습니다/
- 설정 − 속성이 설정되면 호출됩니다. 하나의 인수만 필요합니다.
- 수많은 − true로 설정하면 개체를 반복할 수 있습니다.
- 구성 가능 − 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> 출력

'여기를 클릭' 버튼을 클릭하면 -
