Monday, March 10, 2008

The arguments.callee trick

Inside a JavaScript function, you have an access to the local variable arguments, which simulates the list of all the arguments passed to the function. It's quite useful when you have got a function which might be called with different number of arguments.

But this variable is not a list in really, I mean it's not an instance of Array class and it does have additional attributes. For example .callee and dispite it has been marked as depricated feature since JavaScript version 1.5 then it's still working and interesting stuff.

This attribute arguments.callee refers to the current function by itself. It might look pointless, but in really it's quite handy. Say for example with lambda functions, like I showed once that tricks with (function(){...})(); constructions. Such functions don't have any variables which points on them, so if you need to have some lovely recursion in there, you will need this .callee stuff.

Here you go, another brain-kicker with my faworite camelization task.

alert((function(str) {
var _pos = str.lastIndexOf('_'), suffix = str.substr(_pos+1);
return _pos < 1 ? str : arguments.callee.apply(null, [str.substr(0, _pos)])
+ suffix.charAt(0).toUpperCase() + suffix.substr(1);
})('asdf_asdf_asdf'));

See? Generally you can do it only with a prototype method or with a named function. But if you feel particularly evil and wish it have with a lambda function, you can do it like that with arguments.calle.

This is pretty much it.

No comments: