I'm reading the documentation for the Underscore.js library from DocumentCloud. Many of the functions take an optional context
argument which is not explained. My guess, as one familiar with Ruby is that this is similar to a Ruby binding
. And that it has something to do with what this
means. The extent of my JavaScript usage has been a few jQuery calls and some very boilerplate ajax.
My question: What does context
mean and how should I use it? A good answer should probably contain some information about how JavaScript works as well.
The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object. It's also worth noting _.
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
The underscore is simply a valid character in an identifier, so the method's name is _render . The method Foo can then only be called from within the class which defined it. In JavaScript you can't do this, so it's a typical design pattern to prefix the method with _ to show that it should be treated as private.
Javascript functions take a hidden this
parameter which indicates the context in which the function was called.
Ordinarily, this
is the global object (usually window
). However, when a function is called on an object, this
will be the object that it was called on.
Underscore.js methods that take callback functions take an optional context
parameter. If this parameter is specified, the callback will be called with that context
, meaning that this
inside the callback will be equal to the context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With