๐Ÿ“˜Object.defineProperty()

JS โŸฉ value โŸฉ object โŸฉ property โŸฉ update โŸฉ Object.defineProperty()

define/update a property on an object, and return the object.

// ๐Ÿ”ธ Object.defineProperty(obj, prop, descriptor)
Object.defineProperty(obj, 'age', {
    get() { ... },            // ES6
    set(value) { ... },       // ES6
    enumerable: true,
    configurable: true,
});

// ๐Ÿ”ธ Object.defineProperties(obj, <key/descriptor pairs>)
Object.defineProperties(obj, {

    isMale: {
        value: true,          // โญ๏ธ data property
        writable: true,
    },

    name: {
        get() { ... },        // โญ๏ธ accessor property
        set(value) { ... },
    },

});
  • when creating a new property, the omitted attributes are false by default.

  • when modifying an existing property, the omitted attributes are left unchanged.

The only reason (I can think of) why Object.defineProperty() is static (instead of an instance method) is that an object may not inherit methods from Object.prototype, which means obj.defineProperty() may fail if this is the case.

// โญ๏ธ obj.defineProperty()
// we could still define an instance method if we want to.
Object.defineProperty(Object.prototype, "defineProperty", {
    // by default, writable/enumerable/configurable all false
    value: function(prop, descr) {
        return Object.defineProperty(this, prop, descr); 
    }
});

Last updated