Search code examples
javascriptobjectecmascript-5

What are the main use cases of Object.defineProperty?


I've read about data properties in Javascript Textbook and imagine using Object.defineProperty only in conjunction with accessor properties.

What are the other main use cases of Object.defineProperty to set attributes: [[Enumerable]], [[Writable]], [[Configurable]]? Is it used in frameworks? For what reasons? Is it used in client applications?


Solution

  • Object.defineProperty in general is useful to copy property descriptors from one object to another with the related methods Object.getOwnPropertyNames() and Object.getOwnPropertyDescriptor(), e.g. when merging things into a prototype.

    And as you already mentioned they can be used for getters and setters. The object literal syntax only works when creating new objects. To create new getters/setters in an existing object (e.g. a prototype) you have to use Object.defineProperty(), or copy over the descriptors, as mentioned above.

    [[Enumerable]]

    Useful to avoid enumeration via Object.keys(), for ... in loops, adding properties to array subclasses and the like. This is quite important when adding polyfills to built-in prototypes, especially Object.prototype since you don't want your added methods to suddenly show up in loops as it could break other code which does not do the .hasOwnProperty() check.

    [[Writable]], [[Configurable]]

    Those are not really "useful" in the sense of enabling new programming styles, but they are sanity features that allow you to create read-only properties that can't be overwritten or removed by accident. So yeah, it's great for libraries.

    Object.freeze() / .seal() / .preventExtensions() expand this kind of protection further to the point where you could protect objects sufficiently to create somewhat secure javascript eval sandboxes by protecting the prototypes of of built-in objects.