OK, so now that I'm talking to the nerds, here's some neat Javascript voodoo. I really like monkeying around with runtimes, and one reason that I like Python

myInstance = MyClass() # python
var myInstance = new MyClass(); // Javascript
MyClass* myInstance = new MyClass(); // C++
MyClass* myInstance = [[[MyClass alloc] init] autorelease]; // Objective-C
This also makes for very elegant RPC calls. You can, eg, create a callable instance that you can use like a regular function, but takes care of all the grotty marshalling and connection management behind the scenes. Once you set it up, you can use the instance like any other function:
import xmlrpclib
server = xmlrpclib.ServerProxy('http://time.xmlrpc.com/RPC2')
print server.currentTime.getCurrentTime()
I'm writing a Javascript XML-RPC client library for work and I really wanted to be able to do something that elegant, like:
getCurrentTime = XMLRPCMethod('http://time.xmlrpc.com/RPC2', 'currentTime.getCurrentTime');
alert(getCurrentTime());
But in Javascript, you can only call things that are actual functions. However, since functions are first-class objects, you can bind your own attributes to them like any other object. You can access them from inside the body of the function by using the special variable arguments.callee:
function Greeter(yourName) {
var result = function(timeOfDay) {
alert('Good ' + timeOfDay + ', ' + arguments.callee.yourName);
};
result.yourName = yourName;
return result;
}
greetZ = Greeter('Zobar');
greetP = Greeter('Paul');
greetZ('afternoon'); // 'Good afternoon, Zobar'
greetZ('evening'); // 'Good evening, Zobar'
greetP('evening'); // 'Good evening, Paul'
When I figured this out it blew my mind, and while I doubt its day-to-day practicality, I thought it's a handy tool for Javascripters to have. I also plan to make the XML-RPC library public, once I clean it up a bit, test it in MSIE, and finish the documentation.
- Z
In the past, I've tried to design complex OO stuff in JavaScript, spent a lot of time doing it, had it not work, and wished that netscape had instead made python the standard language of web page scripting.
Considering the number of people who are having success with OO javascript, perhaps I should try things again and give the language one last chance to redeem itself.
I responded to this again on my journal (e:paul), 4370 so that I could include larger code samples. It includes some objects instantiation inside of prototypes.
I responded to this on my journal (e:paul,4369) because the response was too long to fit in a comment. I also added the new [box] style for displaying code.