Overriding read-only props with Object.defineProperty
Creating a non-writable property isn't the final word. In some cases, it is still possible to rewrite these properties. Thankfully, it is not something that is likely to be done by accident. In this recipe, we'll see how to define and redefine non-writable props with Object.define
.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
06-06-redefine-read-only-props
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with amain
function that creates an object. Define a configurable, non-writable property namedprop1
with a random value:
export function main() { const obj = {}; Object.defineProperty(obj, 'prop1',{ writable: false, configurable: true, ...