Defining read-only props with Object.defineProperty
It's not always ideal to have methods that can be overridden. By default, properties that are assigned to an object can be reassigned. We need another option to add functions to an object so they won't be changed.
In this recipe, we'll see how to add non-writable properties to an object with Object.defineProperty
.
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-05-define-readonly-props
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with amain
function that defines a non-writable property, and then tries to write to it:
export function main() { const obj = {}; Object.defineProperty(obj, 'method1',{ writable: false, value: () => { ...