简体   繁体   中英

How to Make a non Extensible Object to extensible?

I need to alter an object which is non extensible. Is there any work around that we can alter this object property ?

I have read the Documentation that says so "There is no way to make an object extensible again once it has been made non-extensible."

Is there any workarounds ? Like Duplicating the object or something?

Another possibility, in addition to duplicating the object, is to create a new object whose prototype is the non-extensible object:

 const object1 = { foo: 'foo', }; Object.preventExtensions(object1); // We can't assign new properties to object1 ever again, but: const object2 = Object.create(object1); object2.bar = 'bar'; console.log(object2); /* This will create a property *directly on* object2, so that `object2.foo` refers to the property on object2, rather than falling back to the prototype's "foo" property: */ object2.foo = 'foo 2'; console.log(object2);

The prototype approach is nice , but it has one limitation compare to cloning. Not all iteration mechanism will go through prototype inherited properties

eg for/in loop is fine but a Object.keys(object2) will not list any inherited property that is not overwritten again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM