javascript - Is there any way to reverse or undo the preventExtensions function? - Stack Overflow

It is possible to make a non extensible object extensible ?var obj = {};Object.preventExtensions(obj);

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
Add a ment  | 

2 Answers 2

Reset to default 5

How 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744144716a4560367.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信