JavaScript: Object.defineProperty

By Xah Lee. Date: . Last updated: .
Object.defineProperty( obj, key, descriptor )
Create/modify a property's attributes. descriptor is Property Descriptor. Return the modified object. Similar to Reflect.defineProperty.
// 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.

Default Values for Property Descriptor

see 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 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 Getter/Setter Properties]

Define Multiple Properties

[see Object.defineProperties]

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Object Object

prototype