concept function context in category javascript
appears as: function context, The function context, function context

This is an excerpt from Manning's book Secrets of the JavaScript Ninja, Second Edition.
When a function is invoked, in addition to the parameters that represent the explicit arguments provided in the function call, an implicit parameter named this is passed to the function. The this parameter, a vital ingredient in object-oriented JavaScript, refers to an object that’s associated with the function invocation. For this reason, it’s often termed the function context.
The function context is a notion that those coming from object-oriented languages such as Java might think that they understand. In such languages, this usually points to an instance of the class within which the method is defined.
Figure 4.3. As the first argument, both the call and apply methods take the object that will be used as the function context. The difference is in the following arguments. apply takes only one additional argument, an array of argument values; call takes any number of arguments, which will be used as function arguments.
![]()
Listing 4.12. Building a forEach function to demonstrate setting a function context
function forEach(list, callback) { #A for (var n = 0; n < list.length; n++) { callback.call(list[n], n); #B } } var weapons = [ { type: 'shuriken' }, { type: 'katana' }, { type:'nunchucks' }]; #C forEach(weapons, function(index){ #D assert(this === weapons[index], #D "Got the expected value of " + weapons[index].type); #D }); #D #A - Our iteration function accepts the collection to be iterated over and a callback function. #B - The callback is invoked such that the current iteration item is the function context. #C - Our test subject #D - Calls the iteration function and ensures that the function context is correct for each invocation of the callback !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[]"} !@%STYLE%@!