Search code examples
javascriptecmascript-5defineproperty

What is a use case for applying defineProperties in javascript?


I have a general question on the practical usage of javascript's ecmascript 5 methods.

e.g.

Object.defineProperties(obj, value, config)

to my knowledge javascript is the driver on the front-end web application. There isn't really a lot of usage in defining variable constant? I can see how enumerable might come in handy if you were to classify attributes. But why is defineProperty so verbose?

and for getters and setters... who would want to hide this functionality inside ecmascript 5, if some old browser runs ecma3, the getter function might not even occur. Why not just use a plain getter function to achieve the same? rather than risking behavior?


Solution

  • First, your syntax is wrong, you are mixing defineProperty and defineProperties. The proper ways are:

    Object.defineProperties(obj, props)
    Object.defineProperty(obj, prop, descriptor)
    

    There isn't really a lot of usage in defining variable constant?

    Well, @danronmoon disagrees.

    I can see how enumerable might come in handy

    Yes, I think non enumerable properties are perfect if you want to add methods to constructors like Object, but don't want for...in lops to iterate them.

    But why is defineProperty so verbose

    I don't find it too verbose. If you mean that the generally preferred way is writable: true, configurable:true, enumerable:true but they default to false, I guess that's because then you can just create the property using dot or bracket notation

    if some old browser runs ecma3, the getter function might not even occur

    Of course, but following this logic web technologies wouldn't evolve.

    Why not just use a plain getter function to achieve the same

    Because it's more cool, flexible, powerful, ...

    For example, they make it easier to make shims for missing native properties. How would you polyfill classList property without getters?