4

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?

Edwin Thomas
  • 466
  • 4
  • 16
  • 2
    `Duplicating the object` Sure https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – CertainPerformance Aug 09 '18 at 06:25

2 Answers2

8

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);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

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

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

pref
  • 1,651
  • 14
  • 24