Object.mixin rather than Object.getOwnPropertyDescriptors

Rick Waldron waldron.rick at gmail.com
Tue Apr 22 15:20:33 PDT 2014


On Tue, Apr 22, 2014 at 1:27 PM, Claude Pache <claude.pache at gmail.com>wrote:

> Hi,
>
> There has been request to add `Object.getOwnPropertyDescriptors` (plural)
> to the standard. Reviewing use cases presented in thread [1] or in older
> thread [2], it seems to me that all of them boil down to copy all own
> properties of one object to another, e.g.,
>
>     Object.defineProperties(target,
> Object.getOwnPropertyDescriptors(source))
>     Object.create(proto, Object.getOwnPropertyDescriptors(source))
>     // etc.
>
> However, this is exactly what `Object.mixin` (deferred from ES6) was
> designed for:
>
>     Object.mixin(target, source)
>     Object.mixin(Object.create(proto), source)
>     // etc.
>
> Besides being shorter to write, `Object.mixin` has the advantages of (1)
> not creating an intermediate object; (2) taking care of some subtleties,
> like rebinding `super` for methods, getters and setters if needed.
>
> Therefore, I think that `Object.mixin` is a better function to have than
> `Object.getOwnPropertyDescriptors`.
>

The latter is not replacing the former; they are different APIs for
different use cases. For example, Object.mixin cannot be used to derive
descriptors from an object and filter then properties by descriptor
attribute value:

  // module.js
  function descriptorsByAttributeFilter(o, filter = {}) {
    var descriptors = Object.getOwnPropertyDescriptors(o);
    var filters = Object.keys(filter);

    return Object.keys(descriptors).reduce((accum, key) => {
      var descriptor = descriptors[key];

      if (filters.every(field => descriptor[field] === filter[field])) {
        accum[key] = descriptor;
      }
      return accum;
    }, {});
  }

  export function writables(o) {
    return descriptorsByAttributeFilter(o, { writable: true });
  }

  export function nonwritables(o) {
    return descriptorsByAttributeFilter(o, { writable: false });
  }


  // script.js

  import {writables, nonwritables} from "module";

  var o = Object.defineProperties({}, {
    thisisnonwritable: {
      value: 1, writable: false
    },
    thisiswritable: {
      value: 2, writable: true
    }
  });

  console.log( writables(o) );
  console.log( nonwritables(o) );


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140422/752fecb5/attachment.html>


More information about the es-discuss mailing list