JavaScript | handler.preventExtensions() Method

The handler.preventExtensions() method in JavaScript is a trap for Object.preventExtensions() method and it returns a boolean value.

Syntax:

const p = new Proxy(target, {
  preventExtensions: function(target) {
  }
});

Parameters: This method accepts single parameter target which holds the target object.

Return value: This method returns a boolean value.

Below examples illustrate the handler.preventExtensions() method in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
const monster1 = {
  canEvolve: true
};
  
const handler1 = {
  preventExtensions(target) {
    target.canEvolve = false;
    Object.preventExtensions(target);
    return true;
  }
};
  
const proxy1 = new Proxy(monster1, handler1);
  
document.writeln(monster1.canEvolve);
document.writeln("<br>");
document.writeln(Object.preventExtensions(proxy1));
document.writeln("<br>");
document.writeln(monster1.canEvolve);
document.writeln("<br>");
  
const proxy = new Proxy({}, {  
   preventExtensions: function(target) {  
   Object.preventExtensions(target);  
   return !Object.isExtensible(target);  
  }  
});  
document.writeln(Object.isExtensible(proxy));
</script>

chevron_right


Output:

true
[object Object]
false
true

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
const p = new Proxy({}, {
  preventExtensions: function(target) {
    document.writeln('preventExtensions()'+"<br>");
    document.writeln(Object.preventExtensions(target)+"<br>");
    return true;
  }
});
  
document.writeln(Object.preventExtensions(p)+"<br>");
  
var x = {  
  first: false  
};  
var y ={  
  preventExtensions(target) {  
    target.canEvolve = false;  
    Object.preventExtensions(target);  
    return true;  
  }  
};  
var proxy = new Proxy(x, y);  
document.writeln(x.first);  
Object.preventExtensions(proxy);  
document.writeln("<br/>");  
document.writeln(x.first); 
</script>

chevron_right


Output:

preventExtensions()
[object Object]
[object Object]
false
false

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

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.