JS: Object.defineProperty

By Xah Lee. Date: . Last updated: .

Object.defineProperty(obj, key, descriptor)

Create a property with specified attribute values (if key doesn't exist), or modify a existing property's attributes.

Return the modified object obj.

descriptor is a syntax for property value and attributes.

[see JS: Property Descriptor]

[see JS: Property Attributes, writable, enumerable, configurable]

// Object.defineProperty example

const x = {};

// define a property and assign its value and attributes
Object.defineProperty(x, "p",
{ value : 3,
writable: true,
enumerable: false,
configurable: true}
);

console.log(x["p"] === 3); // true

Make a property read-only:

// example of setting property to be read-only

// "use strict"

const ob = {"p":3};

Object.defineProperty(ob, "p", { writable: false} );

ob["p"] = 4; // no effect

// if in use strict mode, then it's
// TypeError: Cannot assign to read only property 'p' of #<Object>

console.log( ob["p"] === 3 ); // true

Note: once a property's “writable” attribute is set false, it can't be set back to true.

Reflect.defineProperty

See also: JS: Reflect.defineProperty

Default Values for Property Descriptor

see JS: Property Descriptor

Define Getter Property

Object.defineProperty( object, key, { get : function, enumerable: false, configurable: true } );

const ob = {p1:3};

// add a getter property key "g"
Object.defineProperty(
    ob,
    "g",
    { get : function () { console.log("getter called ") }}
);

ob.g;
// prints: getter called

[see JS: Getter/Setter Properties]

Define Setter Property

Object.defineProperty(object_name, key, { set : function_with_1_param, enumerable: false, configurable: true});

const ob = {p1:3};

// add a setter property key "s"
Object.defineProperty(
    ob,
    "s",
    { set : function (x) { console.log("setter called with arg " +x) }}
);

ob.s = 4;
// prints: setter called with arg 4

[see JS: Getter/Setter Properties]

Define Multiple Properties

[see JS: Object.defineProperties]

JS Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials