Saturday 12 January 2013

Having fun with Javascript

So I've been reading John Resig's "Secrets of the Javascript Ninja". In same ways I regret not reading this any sooner! I thought I knew the concepts of Javacript, but John really digs deep into it and I found myself looking at this curry code example he gave and scratching my head, so I decided to dig more and blog about it. Look for more posts like these where I will be dissecting his snippets more.


Function.prototype.curry = function () {
var fn = this, args = Array.prototype.slice.call(arguments);
return function () {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};


Coming from a backend technology (ie. Java), I was a little baffled by this at first. After all, I thought I knew a thing or two about javascript. Howeveer, the first task was to try to invoke the above function so I can trace the steps to gain a better understanding. The first thing I did was to think of an scenario to call this:


console.log(Math.min.curry('1', '2')('3')); // == 1

Seemed a little unnatural, but sure I can live with that.

Once I figured that out, the next step was to see what the arguments parameters was. You'd think that they were the same, but unfortunately I forgot the fact that it was returning a new function, that means the context of `this` changes (which I knew) AND that the arguments list also changed. Once I figured that out then the rest came easy.

The lesson of the day is: look for places where it's returning a new function...the contexts (this and arguments) will most likely change!
 


No comments:

Post a Comment