Syntactic sugar for using a function as if it were a method of its first argument

Claude Pache claude.pache at gmail.com
Tue May 27 01:17:46 PDT 2014


Often a function can be thought as if it were a method of its first argument. Compare:

	Array.from(obj);   /* vs */   obj.toString()
	Object.getPrototypeOf(obj);   /* vs */   obj.__proto__
	Array.forEach(obj, func);   /* vs */   obj.forEach(func)
	Math.clz32(num);   /* vs */   num.toFixed(2)

and note the inversion of the order of the terms.

So, I propose to introduce syntactic sugar to replace the terms in correct order, e.g.,

	foo{Bar.baz}(...args)
	// or (to be bikeshed)
	foo.{Bar.baz}(...args)

as a synonym of:

	Bar.baz(foo, ...args)

Here are two examples of use:

	window.HTMLFormElement.prototype{Object.getOwnPropertyDescriptor}('elements').get

	document.querySelectorAll('input[type=checkbox][name=Select_ID]:checked').{Array.from}().map(e => e.value).join(',')

The wins are:
* a strict left-to-right order, instead of having methods appearing alternatively at the right and at the left of its main operand, thus improving readability;
* enabling the use of the Existential Operator for the new form, e.g.:

	window.HTMLFormElement?.prototype?{Object.getOwnPropertyDescriptor}('elements')?.get

(Note that `?{` suffers from the same grammar problem as `?[` and `?(`, and the due fix for the two latter would also fix the former.)

—Claude


More information about the es-discuss mailing list