On object extension

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


Hi,

The current proposal for object extension [1] works like the following
(quoting the wiki):
-----
obj.{a:1,b:2,c:3};

// 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};
}
else{
  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:
-----
obj.{a:1,b:2,c:3};

// equivalent to

obj;

(function(){
    var tmp = {a:1,b:2,c:3};
    var names = Object.getOwnPropertyNames(tmp);
    names.forEach(function(n){
        var desc = Object.getOwnPropertyDescriptor(obj, n);
        if(!desc){
            Object.defineProperty(obj, n, {enumerable:true,
                               configurable:true,
                               writable:true,
                               value: tmp[n]});
        }
        else{
            if(desc.configurable || desc.writable){
                Object.defineProperty(obj, n, {value: tmp[n]});
                // other attributes absent to keep existing values
            }
            else{
                  // 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)

David

[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