• JavaScript Video Tutorials

JavaScript Handler defineProperty() Method



The handler.defineProperty() method in JavaScript is used to define new properties or modify existing ones on an object. It is a part of the Proxy object, that enables you to create a proxy for another object and modify its behavior. This method takes three arguments: the target object, the property key, and the property descriptor.

The property descriptor is an object that defines the characteristics of the property, such as its value, whether it's writable, or configurable. This method provides a way to control how properties are accessed and manipulated, enabling advanced features like data validation.

Syntax

Following is the syntax of JavaScript handler.defineProperty() method −

new Proxy(target, {
   defineProperty(target, property, descriptor) {}
});

Parameters

  • target − It holds the target object.
  • property − It is the name or symbol of the property whose description is to be retrievd.
  • descriptor − The descriptor for the property that to be defined or modified.

Return value

This method returns a Boolean value indicating whether the property is successfully defined or not.

Example 1

Let's look at the following example, where we are going to define a new property.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
let x = {};
let y = {
   defineProperty(x, propertyKey, descriptor) {
      document.write(JSON.stringify(descriptor));
      return Reflect.defineProperty(x, propertyKey, descriptor);
   }
};
let z = new Proxy(x, y);
z.tp = 132;
</script>
</body>
</html>

Output

If we execute the above program, it will displays a text on the webpage.

Example 2

Consider another scenario where we are going to modify the existing property.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
let x = {
   tp: 1122
};
let y = {
   defineProperty(x, propertyKey, descriptor) {
      document.write(JSON.stringify(descriptor));
      return Reflect.defineProperty(x, propertyKey, descriptor);
   }
};
let c = new Proxy(x, y);
c.tp = 'WELCOME';
</script>
</body>
</html>

Output

On executing the above script, it will displays a text on the webpage.

Advertisements