A shorthand for Object.defineProperty?

Axel Rauschmayer axel at rauschma.de
Mon Jun 20 09:52:08 PDT 2011


Interesting insight, thanks. If defineProperties() was an instance method, we would have something like the following.

var Multiplier = {
   multiply: function (x) {
       return x * this.FACTOR;
   }
}.defineProperties({
   FACTOR: { value: 3, writable: false }
});

That is, you use the object literal for when the defaults are OK and defineProperties() for special cases, without having to type "Object" and without having to repeat the object you want to add properties to. But with things still changing, this might be a case of YAGNI (introducing easy extensibility where it is never needed).

I keep thinking that something like Java annotations might also work here, especially as Python has adapted them successfully to its needs, via decorators:
http://www.python.org/dev/peps/pep-0318/

I would mainly use property attributes to declare a property as non-configurable and non-writable. That would be the analog to const for variables. Via decorators, one could introduce @const for this purpose.

Axel

On Jun 20, 2011, at 18:22 , Brendan Eich wrote:

> On Jun 20, 2011, at 3:43 AM, Axel Rauschmayer wrote:
> 
>> Would it make sense to include a shorthand for calling Object.defineProperty() to object literals?
>> 
>> Possible benefits:
>> - Extensible, should other property attributes come up in the future
>> - Descriptive
>> - Might obviate the need to have a shorthand for "enumerable" (I usually ignore it and can’t think of any use cases)
>> 
>> === Example ===
>> 
>> var Multiplier = {
>>   FACTOR :: { value: 3, writable: false },
> 
> Do not use :: -- it is wanted for http://wiki.ecmascript.org/doku.php?id=strawman:guards (and used previously in E4X, ECMA-357).
> 
> Allen presented new syntax roughly as verbose at the March TC39 meeting. General reaction was "too verbose".
> 
> Wherefore the #!~ prefixes idea, now in http://wiki.ecmascript.org/doku.php?id=harmony:object_literals -- the syntax there is definitely not final, BTW, but something like it is needed. I've argued we shouldn't try to be "half-verbose", and since ES5 has the very verbose functional API, object initialisers probably will go the other way.
> 
> /be
> 
> 

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list