Assuming the presence of Harmony Proxies in the underlying Javascript engine, how could one construct a CoffeeScript superclass such that extending it would allow a class to define a noSuchMethod method (or methodMessing)?
That method would be called with a name and an argument list if the class (or its superclasses) does not have the method requested.
Nice Question! =D
(Note: i’ve only tested this in Firefox, as it seems is the only browser that supports Harmony proxies.)
This seems to work for missing properties:
Now, it works, but it has a small big caveat: it relies on an “other typed” constructor. That is, the constructor of DynamicObject returns something else than the DynamicObject instance (it returns the proxy that wraps the instance). Other typed constructors have subtle and not-so-subtle problems and they are not a very loved feature in the CoffeeScript community.
For example, the above works (in CoffeeScript 1.4), but only because the generated constructor for Repeater returns the result of calling the super constructor (and therefore returns the proxy object). If Repeater would have a different constructor, it wouldn’t work:
You have to explicitly return the result of calling the super constructor for it to work:
So, as other typed constructors are kinda confusing/broken, i’d suggest avoiding them and using a class method to instantiate these objects instead of
new:Now, for missing methods, in order to have the same interface as requested in the question, we can do something similar in the proxy handler, but instead of directly calling a special method (propertyMissing) on the target when it has no property with that name, it returns a function, that in turn calls the special method (methodMissing):
Unfortunately, i couldn’t find a way to distinguish property accesses from method calls in the proxy handler so that DynamicObject could be more intelligent and call propertyMissing or methodMissing accordingly (it makes sense though, as a method call is simply a property access followed by a function call).
If i had to choose and make DynamicObject as flexible as possible, i’d go with the propertyMissing implementation, as subclasses can choose how they want to implement propertyMissing and treat that missing property as a method or not. The CommandLine example from above implemented in terms of propertyMissing would be:
And with that, we can now mix Repeaters and CommandLines that inherit from the same base class (how useful! =P):