A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-handler-defineproperty-method/ below:

JavaScript Handler defineProperty() Method - GeeksforGeeks

JavaScript Handler defineProperty() Method

Last Updated : 12 Jul, 2025

JavaScript handler.defineProperty() method in Javascript is used to define the new properties and to modify the existing properties directly on an object. It is a trap for Object.defineProper().

Syntax: 

const p = new Proxy(target, {
      defineProperty: function(target, property, descriptor) {
  }
}); 

Parameters: This method accepts three parameters as mentioned above and described below: 

Return value: This method returns a Boolean value which is used to indicate if the property is successfully defined.

Below example illustrates the handler.defineProperty() method in JavaScript:

Example 1: In this example, we will see the use of the handler.defineProperty() method in JavaScript.

javascript
const p = new Proxy({}, {
    defineProperty: function (target, prop, descriptor) {
        console.log('Type : ' + prop);
        return true;
    }
});

const desc = { configurable: true, enumerable: true, value: 10 };
Object.defineProperty(p, 'String', desc);

let xyz = {};
let proxy = new Proxy(xyz, {
    defineProperty: function (target, name, propertyDescriptor) {
        console.log('in defineProperty');
        return Object.defineProperty(target, name, propertyDescriptor);
    }
});
Object.defineProperty(proxy, 'bar', {});  

Output: 

"Type : String"
"in defineProperty"

Example 2: In this example, we will see the use of the handler.defineProperty() method in JavaScript.

javascript
const handler1 = {
    defineProperty(target, key, descriptor) {
        invariant(key, 'define');
        return true;
    }
};

function invariant(key, action) {
    if (key[0] === '_') {
        throw new Error(
            `Invalid attempt to ${action} private "${key}" property`);
    }
}

const monster1 = {};
const proxy1 = new Proxy(monster1, handler1);

console.log(proxy1._propt = 'Handler defineProperty');

Output:

Error: Invalid attempt to define private "_propt" property

Supported Browsers: The browsers supported by handler.defineProperty() method are listed below: 

We have a complete list of Javascript Proxy/handler methods, to check those go through the Javascript Proxy/handler Reference article.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4