Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript's Underscore.js library what does 'context' mean and how do I use it? [duplicate]

Tags:

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.

like image 322
John F. Miller Avatar asked Mar 14 '11 20:03

John F. Miller


People also ask

How does _ each work JavaScript?

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 _.

Why do we use _ in JavaScript?

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.

How do you write an underscore in JavaScript?

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.


1 Answers

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.

like image 80
SLaks Avatar answered Sep 23 '22 03:09

SLaks