It is possible to make a non extensible object extensible ?
var obj = {};
Object.preventExtensions(obj);
obj.abc = "abc"; // this line is ignored which is normal
//is there a way to make obj extensible again
It is possible to make a non extensible object extensible ?
var obj = {};
Object.preventExtensions(obj);
obj.abc = "abc"; // this line is ignored which is normal
//is there a way to make obj extensible again
Share
Improve this question
edited Sep 11, 2018 at 11:15
jenson-button-event
19k13 gold badges96 silver badges163 bronze badges
asked Oct 17, 2016 at 14:34
SAADSAAD
3224 silver badges10 bronze badges
1
- 1 On MDN web docs it says "There is no way to make an object extensible again once it has been made non-extensible." Maybe you could reassign the object? – Todd Commented May 21, 2018 at 21:39
2 Answers
Reset to default 5How about a deep clone?
obj = JSON.parse(JSON.stringify(obj));
obj.abc = "abc"; // this line is now OK
Is OK in local code but any external references that came with obj
will no longer point to the newly formed obj
.
As MDN says:
There is no way to make an object extensible again once it has been made non-extensible.
The easiest way to overe this situation is to clone the object and assign it to a new variable:
const person = {
name: "John",
colors: {
eyes: 'orange',
hair: 'blue'
}
};
Object.preventExtensions(person);
console.log(Object.isExtensible(person)); // false
const extensiblePerson = {...person};
console.log(Object.isExtensible(extensiblePerson)); // true
It is important to note that Object.preventExtensions
only prevents the extension of the top level of the object. In the example above, person.colors
is still extensible, even though its parent object is not.
console.log(Object.isExtensible(person.colors)); // true
console.log(extensiblePerson.colors === person.colors); // true