Analog to Object.getPropertyDescriptor() for *changing* a property value?

David Bruant david.bruant at labri.fr
Thu Jun 23 05:08:11 PDT 2011


Here is a code snippet:
----
var p = {};
(function(){
   var a;
   Object.defineProperty(p, 'a', {get:function(){return a;}, 
set:function(v){a = v;}});
})();

var o1 = Object.create(p);
var o2 = Object.create(p);

o1.a = 1;
console.log(o1.a, o2.a); // 1 1
o2.a = 37;
console.log(o1.a, o2.a); // 37 37
----
'a' is an own property neither of o1 nor o2. (Firefox may say the 
opposite, but I've been told, it's fixed and going to be released on FF 
6 or 7 [1] [2]). a "value" (so to say) is shared among the instances.

David

[1] https://bugzilla.mozilla.org/show_bug.cgi?id=636989
[2] https://bugzilla.mozilla.org/show_bug.cgi?id=637994

Le 23/06/2011 13:19, David Bruant a écrit :
> Hi,
>
> In a the provided example, you assign a value. Can't you just use a 
> getter/setter pair on the prototype chain? It sounds like it would 
> solve your use case (without the syntax sugar). On ES5 - 8.12.5 step 4 
> & 5, the prototype chain is climbed to look up for an accessor and if 
> there is a setter (anywhere on the prototype chain), this setter is 
> called. Combined with the fact that a getter naturally do the same 
> thing for getters, you have your way to change a value "directly on 
> the prototype chain".
> Of course, if you want to change the property descriptor on the 
> prototype chain, none of what I said apply.
>
> David
>
>
> Le 21/06/2011 17:24, Axel Rauschmayer a écrit :
>> As a loose analog to the prototype-chain-traversing 
>> getPropertyDescriptor(), I would still like to have something that 
>> allows one to easily *change* properties higher up the prototype 
>> chain (e.g. to use a prototype to share state).
>>
>> Maybe it would be enough to just have Object.getDefiningObject(obj, 
>> propName):
>> http://www.mail-archive.com/es-discuss@mozilla.org/msg06652.html
>>
>> But I can also imagine syntactic sugar:
>>          obj.foo := "abc"
>> desugars to
>>          Object.getDefiningObject(obj, "foo").foo = "abc"
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss



More information about the es-discuss mailing list