Does Javascript have something like Ruby's method_missing feature?

user310291 picture user310291 · Mar 20, 2012 · Viewed 13.1k times · Source

In Ruby I think you can call a method that hasn't been defined and yet capture the name of the method called and do processing of this method at runtime.

Can Javascript do the same kind of thing ?

Answer

Luciano Ramalho picture Luciano Ramalho · Jan 29, 2013

method_missing does not fit well with JavaScript for the same reason it does not exist in Python: in both languages, methods are just attributes that happen to be functions; and objects often have public attributes that are not callable. Contrast with Ruby, where the public interface of an object is 100% methods.

What is needed in JavaScript is a hook to catch access to missing attributes, whether they are methods or not. Python has it: see the __getattr__ special method.

The __noSuchMethod__ proposal by Mozilla introduced yet another inconsistency in a language riddled with them.

The way forward for JavaScript is the Proxy mechanism (also in ECMAscript Harmony), which is closer to the Python protocol for customizing attribute access than to Ruby's method_missing.