getter / setters

Oliver Hunt oliver at apple.com
Thu May 20 11:45:46 PDT 2010


On May 20, 2010, at 11:37 AM, Irakli Gozalishvili wrote:

> Hi,
> 
> Sorry if my question is stupid or does not really belongs here. I will be thankful to get some clarification on es specs since I just discovered that my interpretation of how getter / setters are supposed to behave appears to be different from the behavior in observed in modern browsers.
> 
> var foo = Object.create({}, {
>     bar: { 
>         get: function() { 
>             return this._foo;
>         },
>         set: function(value) {
>             return this._foo = 'Hello ' + value;
>         } 
>     }
> });
> 
> var bar = foo.bar = 'setter';
> if (foo.bar !== bar) throw new Error('Unexpected');
> 
> The code will throw an error cause bar will be 'setter' while foo.bar will be 'Hello setter'.  I was expecting that `bar' would've get value returned by a setter (or at least getter of foo). And this is not the case nor with FF nor with Safari implementations. Behavior is the same if getters and setters are used instead. Is it expected behavior ? If answer is yes, is there any point of returning anything from setter ?
There is no point in returning anything from a setter.

This is due to the semantics of the assignment operator, not setters -- the result value of an assignment is the righthand side of the expression. 

eg. for any expression
<some lvalue> = someObject.property = <expr>

the behaviour is equivalent to

temp = <expr>
someObject.property = temp
<some lvalue> = temp

(ignoring the need to resolve the destinations in the correct order)

> I am also afraid that this might break some of the frameworks in rare cases like in this example above. (a = b = c is commonly used syntax)

This has always been the behaviour of assignment.

--Oliver



More information about the es-discuss mailing list