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

StackOverflow https://stackoverflow.com/questions/5304039

  •  24-10-2019
  •  | 
  •  

Question

This question already has an answer here:

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top