Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript | handler.preventExtensions() Method

  • Last Updated : 28 Sep, 2021

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: 
 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

javascript




<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>

Output: 
 

true
[object Object]
false
true

Example 2: 
 

javascript




<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>

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :