📘Object.defineProperty()

JSvalueobjectpropertyupdate ⟩ 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