I am trying to pass an object to another module; My object includes {__proto__: { value: 1}}
.
const x = {
__proto__: { value: 1 }
}
console.log(x)
what I expected as a result was
{__proto__: { value: 1 }}
but what I got was
{}
and I did try using "__proto__"
.
The only way I got it to work was by using
JSON.parse("{"__proto__": { "value": 1 }}")
but I really don’t think this is very performant solution (would require a lot of code configuring)
Is there a method to get it to be read like the parse and have
JSON.stringify(x)
result in '{"__proto__": { "value": 1 }}'
not '{}'
2
Answers
The
__proto__
key in object literals is treated specially and initialises the internal [[prototype]] of the new object. It does no matter whether you write{__proto__: …}
or{"__proto__": …}
for that. (This is related – by name only – to theObject.prototype.__proto__
getter/setter, but it is a separate and non-deprecated feature of object literals).To create a normal own property with the literal name
__proto__
, you can use a computed property name:Certainly a very hacky solution but you could define custom
JSON.stringify()
logic using thereplace?
parameter. If a key ofx
is an empty string you can include the__proto__
manually.