gfazioli
11/4/2017 - 10:56 AM

Context, Call and Apply

/*
 In JavaScript, the variable "this" always refers to the current context. 
 By default, "this" refers to the window object. Within a function this context can change,
 depending on how the function is called.

 All event handlers in jQuery are called with the handling element as the context.

 You can specify the context for a function call using the function-built-in methods call and apply. 
 The difference between them is how they pass arguments. 
 Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.
*/

$( document ).ready(function() {
  // this refers to window.document
});
$( "a" ).click(function() {
  // this refers to an anchor DOM element
});


function scope() {
  console.log( this, arguments.length );
}
scope() // window, 0
scope.call( "foobar", [ 1, 2 ] ); // "foobar", 1
scope.apply( "foobar", [ 1, 2 ] ); // "foobar", 2