On object extension

David Bruant bruant.d at gmail.com
Mon Nov 28 11:32:42 PST 2011


The current proposal for object extension [1] works like the following
(quoting the wiki):

// is equivalent to

Object.defineProperties(obj, {
   a: {value: 1, enumerable: true, writable: true, configurable: true},
   b: {value: 2, enumerable: true, writable: true, configurable: true},
   c: {value: 3, enumerable: true, writable: true, configurable: true}

It is an interesting improvement from ES5.1, but has some issues.
First, if obj already has a non-configurable property 'a', this will
throw (not to mention if obj is non-extensible). And unfortunately,
doing something like:
if(Object.getOwnPropertyDescriptor(obj, 'a').configurable){
  obj.{a:1, b:2, c:3};
  obj.{b:2, c:3};
does not scale at all.

What about taking a more conservative approach and only add properties
when either they don't exist or they exist and are configurable or writable?
Something more like:

// equivalent to


    var tmp = {a:1,b:2,c:3};
    var names = Object.getOwnPropertyNames(tmp);
        var desc = Object.getOwnPropertyDescriptor(obj, n);
            Object.defineProperty(obj, n, {enumerable:true,
                               value: tmp[n]});
            if(desc.configurable || desc.writable){
                Object.defineProperty(obj, n, {value: tmp[n]});
                // other attributes absent to keep existing values
                  // Nothing. It's a constant!

I can think of any case where this would throw.
Moreover, if one really cares about the state of a given property before
and after the extension, she can inspect the object.

Another feature which could be handy is extending an object with another
already existing object (aka mixins?).
This feature could be more straightforward, because there is a way for
the author to filter out properties before the extension (unlike with a
syntax-based feature as I showed above)


[1] http://wiki.ecmascript.org/doku.php?id=harmony:object_literals
[2] http://nodejs.org/docs/v0.4.5/api/http.html#http.request

More information about the es-discuss mailing list