JavaScript proxy() 객체는 객체 또는 함수를 래핑하고 속성 액세스, 함수 호출 등과 같은 기본 작업을 위한 사용자 지정 작업에 사용됩니다.
다음은 JavaScript의 proxy() 객체에 대한 코드입니다 -
예시
<!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;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JavaScript Proxy() Object</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to access object values using proxy object
</h3>
<script>
let sampleEle = document.querySelector('.sample');
const test = {
Name: 'Rohan Sharma',
birthYear: 1990,
};
const handler = {
get: function(target, objectKey) {
if (objectKey === 'FirstName') {
return target.Name.split(' ')[0];
}
if (objectKey === 'CurrentAge') {
let date = new Date();
return date.getFullYear() - target.birthYear;
} else {
return Reflect.get(target,objectKey);
}
}
};
const proxy1 = new Proxy(test, handler);
document.querySelector('.Btn').addEventListener('click',()=>{
sampleEle.innerHTML += 'proxy1.Firstname = ' + proxy1.FirstName + '<br>';
sampleEle.innerHTML += 'proxy1.CurrentAge = ' + proxy1.CurrentAge + '<br>';
})
</script>
</body>
</html> 출력

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