Thursday, February 15, 2007


Javascript: Oh, Duh

I'm sure some people are going to fall off their chairs when I say that I only just discovered this. It's very much a forehead-slap moment.

If you call a method in javascript like it was a parameter, you'll get back the source for that method. As an example, imagine you've got a method like this:
function simpleMethod()
var someVar = 5;
return someVar + 4;
If you do something like this:
var anotherVar = simpleMethod();
then anotherVar is going to be 9. If on the other hand, you do something like this:
var anotherVar = simpleMethod;
then anotherVar is going to be "function simpleMethod() { var someVar = 5; return someVar + 4; }".

I realise how basic this is. But suddenly a whole lot about JavaScript makes a lot more sense now.


It's actually better than that -- you only see the source when you print it (and it gets converted to a string).

It's actually still a full function. Functions are objects in Javascript, and can be passed around as much as you like.

You can do:

myfunc = function(message) { alert(message); }

myotherfunc = myfunc;

All that sort of thing. Then you can call the variable:

myotherfunc("my message");

You can also make functions that return functions:

function maker(message)
return function() { alert(message); }

helloFunc = maker("Hello");
helloFunc(); // alerts with "Hello"

It's lots of fun. Closures and currying ahoy!
And therein lies the benefit of what they dynamic typing, or sometimes 'duck' typing.
(if it looks like a duck, and quacks like a duck, then it's a duck...if you don't call it, then it must be a string...) There's no way C or Java would compile anything that zany!

Bruce Eckel explains it really nicely here, as well as insisting that developers do unit testing. (Don't all you Simons miss me nagging you to do that?)
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?