javascript function scope

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.

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

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.

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

Tiene una función llamada createDelegate que sirve
para setear el scope
al pasar la funcion como handler:

Ext.MessageBox.confirm('Confirmación', 'Está seguro?',
resuelto.createDelegate(this) );

Don’t Stop Here

More To Explore