re-using getters and setters in object literals

Brendan Eich brendan at
Tue Aug 19 17:30:54 PDT 2008

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, 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 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:

(look for my comment dated 2007/05/04 12:21). Note also the loss of  
string and number property names.

> As it stands the algorithms require a new function object be created
> for each getter and setter with each object creation process that
> following from the use of an object litters. This strikes me as
> possibly being less than optimal in some circumstances, and
> certainly would preclude the possibility of using functions
> returned from the - bind - method or inner functions that
> exploit closures as getters and setters in object literals (except
> the closures formed by the evaluation of the PropertyAssignments).
> I imagine that the productions for these possibilities would be
> something like:-
>     get PropertyName : AssignmentExpression
>     set PropertyName : AssignmentExpression
> - where a TypeError would be thrown in the event that
> AssignmentExpression did not evaluate as a function object
> following GetValue (i.e. is not an object or does not have a [[Call]]
> method). With AssignmentExpression used here to allow, for example,
> the return value from a function call to provide the function
> refence value used as the getter/setter (or even - new Function( .. )
> -).
> Richard Cornford.

I'm in favor, for ES-Harmony if not ES3.1.


More information about the Es-discuss mailing list