最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
发布评论

评论列表(0)

  1. 暂无评论