re-using getters and setters in object literals

Richard Cornford Richard at litotes.demon.co.uk
Tue Aug 19 19:42:23 PDT 2008


Brendan Eich wrote
> On Aug 19, 2008, at 4:55 PM, Richard Cornford wrote:
> 
>> In the current ES 3.1 draft we have:-
>>
>> PropertyAssignment :
>>     PropertyName : AssignmentExpression
>>     get PropertyName ( ) { FunctionBody }
>>     set PropertyName ( PropertySetParameterList ) { FunctionBody }
>>
>> - in which I don't see any provision for re-using function
>> objects as getters and setters. That is, there is no mechanism
>> for defining/creating a function object elsewhere and then using
>> it as a getter or a setter for an object literal. Has that
>> possibility been rejected, or never raised?
> 
> I've raised it,

So that means rejected. A pity.

> since my original getter/setter implementation (1998  
> era) allowed this:
> 
> function sharedGetter() { /* voluminous code here */ }
> 
> var obj = {
>   prop1 getter: sharedGetter,
>   prop2 getter: sharedGetter,
>   ...
> };
> 
> The getter: and setter: punctuator-sequences consisted of two
> tokens; getter and setter were only contextually reserved. There
> were getter=  and setter= assignment operators, too; these have
> been superseded in SpiderMonkey and Rhino by __defineGetter__
> and __defineSetter__.

The - Object.defineProperty - method seem to allow for assigning
getters and setters using any function reference, so re-using
functions is possible. (And that method will throw a TypeError if
the getter/setter values are not callable.) So it is not that the
action cannot be taken in ES 3.1, it is just going to mean using
an object literal and then passing the result through -
Object.defineProperty - (possibly repeatedly) in order to assign
the function(s). That is going to be pretty messy in comparison to
being able to do it all inside one object literal.

> The inability to share a getter or setter in the syntax that
> replaced the above:
> 
> var obj = {
>   get prop1() { return sharedGetter(); },
>   get prop2() { return sharedGetter(); },
>   ...
> };
> 
> was indeed noted here:
> 
> http://wiki.ecmascript.org/doku.php?id=proposals:getters_and_setters
> 
> (look for my comment dated 2007/05/04 12:21). Note also the loss of  
> string and number property names.

Well string and number literal property names (even for getters
and setters) appear to be in ES 3.1, which is a good thing IMO.
 
<snip>
> I'm in favor, for ES-Harmony if not ES3.1.

:)

Richard Cornford.


More information about the Es-discuss mailing list