JavaScript handler.preventExtensions() method in JavaScript is a trap for Object.preventExtensions() method. New properties cannot be added to an object when extensions are disabled. It returns a boolean value.
Syntax:
const p = new Proxy(target, { preventExtensions: function(target) { } });
Parameters: This method accepts a single parameter target that holds the target object.
Return value: This method returns a boolean value.
Below examples illustrate the handler.preventExtensions() method in JavaScript:
Example 1: In this example, we will see the use of the handler.preventExtensions() method in JavaScript.
javascript
const p = new Proxy({}, { preventExtensions: function (target) { console.log( 'preventExtensions()' ); console.log(Object.preventExtensions(target)); return true ; } }); console.log(Object.preventExtensions(p)); let x = { first: false }; let y = { preventExtensions(target) { target.canEvolve = false ; Object.preventExtensions(target); return true ; } }; let proxy = new Proxy(x, y); console.log(x.first); Object.preventExtensions(proxy); console.log(x.first); |
Output:
true [object Object] false true
Example 2: In this example, we will see the use of the handler.preventExtensions() method in JavaScript.
javascript
const p = new Proxy({}, { preventExtensions: function (target) { console.log( 'preventExtensions()' ); console.log(Object.preventExtensions(target)); return true ; } }); console.log(Object.preventExtensions(p)); let x = { first: false }; let y = { preventExtensions(target) { target.canEvolve = false ; Object.preventExtensions(target); return true ; } }; let proxy = new Proxy(x, y); console.log(x.first); Object.preventExtensions(proxy); console.log(x.first); |
Output:
preventExtensions() [object Object] [object Object] false false
Supported Browsers: The browsers supported by handler.preventExtensions() method are listed below:
- Google Chrome 49 and above
- Edge 12 and above
- Firefox 22 and above
- Opera 36 and above
- Safari 10 and above
We have a complete list of Javascript Proxy/handler methods, to check those go through the Javascript Proxy/handler Reference article.