0

I'm trying to inherit default spec properties, such that, when I create specific overwriting values in inheriting specs, I will still have access to (through inheritance) the unmodified spec values:

let default_boltSpec = {
  head_diameter: 2,
  shaft_diameter: 0.8,
};
Object.freeze(default_boltSpec);

let derivedBoltSpec = Object.create(default_boltSpec);
console.log( "derivedBoltSpec:", derivedBoltSpec );

Object.assign(derivedBoltSpec , {
  head_diameter: 1.5,
});

The weird thing is that I seemingly am not allowed to "overwrite" inherited values! How can values that are strictly on the prototype chain in any way interfere with what properties I am allowed to put on my object?

EDIT: This screenshot shows the effect of running the above code snippet in the Firefox web developer console: enter image description here

This image reveals that Object.create does not add any properties to the created object. This is in harmony with the documentation.

1 Answers1

0

You've frozen the object. This will freeze the property values as well.

From the context, I think what you want to use is seal instead of freeze. For example,

let default_boltSpec = {
  head_diameter: 2,
  shaft_diameter: 0.8,
};
Object.seal(default_boltSpec);

let derivedBoltSpec = Object.create(default_boltSpec);

Object.assign(derivedBoltSpec , {
  head_diameter: 1.5,
});
console.log( derivedBoltSpec)

Here are the docs for seal

EDIT: You'll have to make the properties writable again. You can do this using Object.defineProperty. But you'd essentially be looping over all the properties and making them writable. For example,

Object.defineProperty(derivedBoltSpec 'head_diameter:', { value: 1.5, enumerable: true, configurable: true, writable: true });
ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • I've frozen the *prototype* object ('default_boltSpec'). The object I'm trying to modify is 'derivedBoltSpec' and it has not been frozen. –  Mar 15 '18 at 16:01
  • But I'm not even trying to change the properties of the prototype object. That's why this is very confusing. The frozen prototype object is never modified after its creation. –  Mar 15 '18 at 18:53
  • 1
    The frozen property propagates with inheritance. With object.create you're basically copying the whole object with all it's properties with their behaviour and it's prototype(in __proto__) to the new object. – ayushgp Mar 15 '18 at 18:57
  • While your explanation would indeed explain the error message, it relies on a hypothesis which has evidence against it: the hypothesis that any properties at all get copied from the first argument of Object.create onto the created object. I've added this evidence in my question. –  Mar 15 '18 at 19:57
  • 1
    Have a look at this answer: https://stackoverflow.com/a/19698581/3719089 It was wrong of me to say that properties are copied, I should've clearly mentioned that. – ayushgp Mar 15 '18 at 22:12