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

Jürg Lehni lists at
Wed Jun 30 16:14:22 PDT 2010

On 30 Jun 2010, at 18:26, Jeff Watkins wrote:

> Just out of curiosity, what's wrong with the idiomatic Javascript way of passing an object literal as your last constructor argument? So your example becomes:
> 	var stopButton = new ImageButton(this, {
> 		image: getImage('stop.png'),
> 		size: buttonSize,
> 		toolTip: 'Stop Running Scripts',
> 		onClick: stopAll
> 	});
> Granted, you wind up with an extra comma...

The difference of my proposal is that this would work with any constructor: All the properties of the provided object literal would be mixed into the created object. Your proposal would require special constructors for each type that would accept an optional last argument containing an object with all these properties. Each of these constructors would then have to iterate over the properties and copy them over. I proposed to automate this, as from my experience it appears to be something that would often be of great use.

Just to clarify. These two examples would produce the same result:

	var stopButton = new ImageButton(this) {
		image: getImage('stop.png'),
		size: buttonSize,
		toolTip: 'Stop Running Scripts',
		onClick: stopAll

	var stopButton = new ImageButton(this);
	stopButton.image = getImage('stop.png');
	stopButton.size = buttonSize;
	stopButton.toolTip = 'Stop Running Scripts',
	stopButton.onClick = stopAll;

The ImageButton constructor would not provide any magic itself, and it would never actually see the object literal. This would work out of the box with any constructor.

In this particular example, ImageButton is actually a Java class that is used through Rhino's Java bridge feature. Setting image / size / toolTip properties then internally calls the setImage / setSize / setToolTip bean property setters. As far as I understand, the proposal by Allen Wirfs-Brock to use Object.create for this would there not work for two reasons: ImageButton.prototype is not available for such native java classes, and overriding properties through new property definitions would not cause the previous setters to be called.


More information about the es-discuss mailing list