fbpx

javascript function scope

February 19, 2008

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
scope.call("foobar", [1,2]); // "foobar", 1
scope.apply("foobar", [1,2]); // "foobar", 2


EXTJS
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) );



avatar
Gonzalo Escribano

Ver entradas

Most Recent

June 9, 2022

¿Qué son las DAO y cuáles son sus beneficios?

Es común en la historia contemporánea que haya cambios a partir de los avances en el campo de la...

Read More

June 2, 2022

¿Qué son las DeFi y por qué son el futuro de las finanzas?

Es común en la historia contemporánea que haya cambios a partir de los avances en el campo de la...

Read More

May 27, 2022

How to start a successful product build from scratch?

Creating a product from scratch could be a huge challenge. To achieve your business goals it’s important to develop...

Read More