Can I enforce that the prototype of an object not be changed?
Note! There are some requirements:
- The object should behave just like a regular object literal (add/remove/configure/modify properties and descriptors on the object),
- with literally the only new limitation being that the prototype is permanent.
So other than the prototype being permanent, I don't want to add any other limitations (tools like Object.seal/freeze/preventExtensions
impose more limitations on the object).
Would I have to monkey-patch
I came up with a monkey-patch to do what I wanted, exposing a
lockPrototype
function in the following snippet.The only problem that I am aware of is that if some other code runs before my code, then they can get original references to
Object.setPrototypeOf
and the setter from theObject.prototype.__proto__
descriptor, and thus work around my monkey-patch. But for most cases I think it would work. A native implementation wouldn't have this problem.Before I accept my own answer, are there any other problems with it?
Here's the example (the part labeled
lockPrototype.js
is the implementation, and the part labeledtest.js
is how it could be used):(fiddle: https://jsfiddle.net/trusktr/Lnrfoj0u)
The output that you should see in Chrome devtools console is:
One option is Object.preventExtensions() (note, this locks the whole object from extensions, doesn't lock only the prototype from being modified):