Syntax Proposal: Allow Java-like Object Literals after constructor calls to set properties on created objects.

Mike Samuel mikesamuel at gmail.com
Tue Jun 8 12:57:10 PDT 2010


A lot of people put opening semicolons on a new line, including the
Rhino authors.
How would semicolon insertion in this proposal interact with that
formatting convention?
    var runnable = new java.lang.Runnable()
    {
      run: function ()
      {
      }
    };


2010/6/8 Jürg Lehni <lists at scratchdisk.com>:
> This simple proposal is inspired by an extension of Rhino that currently allows to implement its syntax for anonymous Java interface implementation. Here an example that creates an anonymous class implementing the Runnable interface and defining the run method in an anonymous object literal that (mimicking a Java code block) immediately following the constructor call:
>
> var runnable = new java.lang.Runnable() {
>        run: function() {
>        }
> };
>
> When looking deeper into how Rhino achieves this syntax, I found out that it simply appends the following anonymous object literal to the list of arguments of whatever constructor came before. So the following code works in Rhino and prints the content of the hello string to the console:
>
> function Test(obj) {
>        print(obj.hello);
> }
>
> new Test() {
>        hello: 'Greetings, I am an anonymous object literal'
> };
>
> For the Illustrator scripting plugin http://scriptographer.org I came up with the convention to (ab)use this non-standard feature to allow setting of properties on freshly created objects, by extending the underlying Java proxy objects to automatically detect such a passed object literal, iterate through its properties and set them on the newly created object (In Scriptographer it is then also removed from the argument list). Soon it became apparent that this is very useful and also leads to cleaner code. I therefore started to wonder if this would make sense as an syntax extension in ES5. Here another example.
>
> function MyConstructor(param) {
>        print(param); // Should not print the object literal
> }
>
> var obj = new MyConstructor() {
>        property: 'This will be automatically set on the created object'
> };
>
> print(obj.property); // 'This will...created object'
>
> So far I cannot see any syntax conflicts.
>
> I am wondering what you all think of this proposal and look forward to your thoughts.
>
> Jürg
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list