Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Handler preventExtensions() Method

JavaScript Handler preventExtensions() Method

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments