Why is it Object.defineProperty() rather than this.defineProperty() (for objects)?

It’s to avoid collisions – in general, issues with objects that do not have the property with the value that you expect.
Objects in JS are often used as key-value-maps, and the keys can be arbitrary strings – for example __defineGetter__, hasOwnProperty or something less special. Now when you want to invoke such a function on an unknown object – like hasOwnProperty is often used in generic enumeration functions, where any JSON might be passed in – you can never be sure whether you got a overwritten property (that might not even be a function) or the original which you want, or whether the object inherits the property at all. To avoid this issue (or also this IE bug), you’d have to use Object.prototype.hasOwnProperty.call – that is ugly.

So, namespacing all those functions on Object is only useful, it’s a cleaner API that separates the reflection methods from the object’s application interface. This also helps optimisation (simplifying static analysis) and makes it easier to restrict access to the reflection API in sandboxes – at least that was the design idea.

You might be happy to have a defineProperty around in the prototype, but you can only use it safely when working with known objects. If you still want it (as you know when to use and when not), you could use

Object.defineProperty(Object.prototype, "defineProperty", {
    writable: true,
    enumberable: false,
    value: function(prop, descr) {
        return Object.defineProperty(this, prop, descr); 
    }
});

Leave a Comment