I’ve been dipping my toes into Javascript and now looking at the following piece of code:
var router = new(journey.Router)({
...
});
router.root.bind(function (res) { res.send("Welcome") });
Question: What is the root function above bound to? What does this binding do?
I understand that ‘bind()’ is supposed to bind the execution of a function to a specified object as a context. I do not understand how a function/method can be bound to an other function. All of the references I have looked at are talking about binding to an object.
‘root’ is a getter method defined in journey.js (at line 145) as
which is simply an expedient shorthand for
And in this context, the call to bind will associate the provided callback function with the route defined as root, such that any requests that match the root path (‘/’) will be answered by the string ‘Welcome’.
UPDATED
Upon further examination of the journey.js source, it appears the use of bind() in this context is not an example of currying at all.
Rather this particular bind() is defined as a function of the object returned by route() (which in turn is called by get()) in journey.js at line 131, and is simply used to set (or bind) the handler for a particular route.
IMPORTANT: This call to bind() IS NOT the same as Function.prototype.bind().
I’m leaving my previous answer below because I believe the information regarding currying still has value in this situation.
This use of Function.prototype.bind() is called ‘currying’ and is used to provide a new function which has values already provided for one or more of its expected arguments.
A simple example of currying would be if you assume:
function addSome(amount, value) {
return value + amount;
}
which could be curried to produce a new function:
var addOne=addSome.bind(1);
and is exactly the same as:
function addOne(value) {
return addSome(1,value);
}
Currying is a feature from [functional programming].
See [bind – MDN Docs] for an explanation of bind() and [currying] for a formal definition of this technique.
[functional programming]:http://en.wikipedia.org/wiki/Functional_programming
[bind – MDN Docs]:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
[currying]:http://en.wikipedia.org/wiki/Currying