JavaScript Proxy() Object

JavascriptWeb DevelopmentObject Oriented Programming

The JavaScript proxy() object wraps an object or function and is used for custom actions for fundamental operations like accessing property , invoking function etc.

Following is the code for proxy() object in JavaScript −

Example

 Live Demo

<!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>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 11-May-2020 14:16:25
Advertisements