JavaScript handler.defineProperty() Method - JavaScript Tutorial

JavaScript handler.defineProperty() Method

BLUF: This tutorial on JavaScript handler.defineProperty() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript handler.defineProperty() Method

Understanding JavaScript handler.defineProperty() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The handler.defineProperty function serves the purpose of establishing new properties. Additionally, it enables direct alterations of existing properties on an object. This function acts as a trap for Object.defineProperty. It can be utilized in two specific scenarios.

  • When it is necessary to guarantee cross-browser compatibility for getters and setters.
  • Whenever there is a need to create a custom property accessor.
  • Syntax

Example

defineProperty: function(target, property, descriptor)

Parameters

Target : The target object.

Property : Retrieved property description.

Descriptor: The characteristic that is being specified or altered.

Return value

This method returns a Boolean

Browser Support

Chrome 49
Edge 12
Firefox 18
Opera 36

Example 1

Example

var target = {}

target.foo = 'bar'

document.writeln(Object.getOwnPropertyDescriptor(target, 'foo'))

Output:

Output

[object Object]

Example 2

Example

var xyz = {};

var proxy = new Proxy(xyz, {

  defineProperty: function(target, name, propertyDescriptor) {

document.writeln('in defineProperty');

return Object.defineProperty(target, name, propertyDescriptor);

  }

});

Object.defineProperty(proxy, 'bar', {} );

Output:

Output

in defineProperty

Example 3

Example

var xyz ={};

var hu = {};

var proxy = new Proxy(xyz, {

   defineProperty: function(target, name, propertyDescriptor) {

    document.writeln('Learn Java Script');



       return Object.defineProperty(target, name, propertyDescriptor);

  }

      });

var pro= new Proxy(hu, {

  defineProperty: function(target, name, propertyDescriptor) {

    document.writeln('Proxt Method ');

       return Object.defineProperty(target, name, propertyDescriptor);

}

      });

   Object.defineProperty(proxy, 'bar', {} );

   Object.defineProperty(pro, 'hug', {} );

Output:

Output

Learn Java Script Proxt Method

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience