I`m a newbie at JavaScript trying to understand this tutorial about currying from Oreilly JavaScript Cookbook.
Could someone be kind enough to explain this program i
If you dont mind a suggestion, start with Javascript: The Good Parts. Follow that up with either Javascript Patterns, or Secrets of the Javascript Ninja for more advanced techniques. Cookbooks are more for canned solutions to problems then a learning resource.
Matt Ball did a good job explaining whats going on. If you are a beginner, I wouldn't sweat trying to figure out curry functions anyways. That aside, IMO this curry function is terrible. This is how I would change it
// this is doing binding and partial function application,
// so I thought bind was a more appropriate name
// The goal is that when you execute the returned wrapped version of fn, its this will be scope
function bind(fn, scope) {
// arguments is an implicit variable in every function that contains a full list
// of what was passed in. It is important to note that javascript doesn't enforce arity.
// since arguments is not a true array, we need to make it one.
// a handy trick for this is to use the slice function from array,
// since it will take arguments, and return a real array.
// we are storing it in a variable, because we will need to use it again.
var slice = Array.prototype.slice,
// use slice to get an array of all additional arguments after the first two
// that have been passed to this function.
args = slice.call(arguments, 2);
// we are returning a function mostly as a way to delay the execution.
// as an aside, that this is possible in a mainstream language is a minor miracle
// and a big part of why i love javascript.
return function() {
// since functions are objects in javascript, they can actually have methods.
// this is one of the built in ones, that lets you execute a function in a different
// context, meaning that the this variable inside the
// function will actually refer to the first argument we pass in.
// the second argument we are jamming together the arguments from the first function
// with the arguments passed in to this wrapper function, and passing it on to fn.
// this lets us partially apply some arguments to fn when we call bind.
return fn.apply(scope, args.concat(slice.call(arguments)));
}
}
JavaScript, while wonderful, is horribly verbose. Needlessly repeating var while defining your bindings just adds a lot of noise. Also, there is no need to painfully build a real array like that, slice will take arguments and give you a real array back. Especially in this case where we are using it twice, AND we actually want to slice out the first two args anyways. Finally, when you apply and your first arg is null, JavaScript will apply the global object for you. There is no need to do that explicitly.
IMO my 5 line function body kicks the crap out of o'reillys 11 lines, and IMO it is much more readable.