What might you do with a feature like this? If you found this page I imagine you already have a few ideas in mind but if not the Ruby on Rails framework contains many examples of this technique. Ruby on Rails uses Ruby's method_missing for all sorts of "meta-programming" magic like dynamic finders such as ActiveRecord::Base#find_by_login_and_password('bob', 'cheese').
So I can't leave you without an example...If your browser is so inclined, the following text box will allow you to enter any call you like against the "example" object and will use __noSuchMethod__ to spit back information about the call.
The code that sets up the "example" instance looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var example = { | |
__noSuchMethod__: function(id, args) { | |
alert("You called " + id + " on example with " + args.length + " arguments [" + args.join(",") + "]"); | |
} | |
} | |
document.getElementById("evalButton").onclick = function() { | |
eval(document.getElementById("evalText").value); | |
} |
I, for one, would really like to see a feature like this become a Javascript standard.
Hey, if you are interested in learning more about Javascript I would recommend the following books: Javascript: The Definitive Guide, Pro Javascript Techniques, and Prototype and script.aculo.us: You Never Knew JavaScript Could Do This!
Oh yeah, one last thing - since Javascript objects are pretty much just hashes this type of method missing technique really only needs hashes to be extended to allow a default value to be specified like you can do with a Ruby Hash. This would result in the possibility of writing code like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var example = new Hash(function() { | |
alert(arguments.callee + " called on example with " + arguments.length + " arguments "); | |
}); |
I'm not sure what type of syntax could be offered if the object didn't begin its life as a Hash.