I’m wondering how to deal with member variables in closures in JavaScript. The following code alerts “6”.
function testy()
{
function blah()
{
this.a = 5;
this.func = function()
{
this.a = 6;
alert(this.a);
}
}
var x = new blah;
x.func();
}
but this code alerts 5.
function testy()
{
function execute(func)
{
func();
}
function blah()
{
this.a = 5;
this.func = function()
{
execute(function()
{
this.a = 6;
});
alert(this.a);
}
}
var x = new blah;
x.func();
}
How do I pass a closure which still accesses the member variables of the enclosing object?
Your calling the function as
func();and by default without specifying a contextthiswill resolve to the global context which iswindowin the browser.. There are three options you can use here.make
thislocalNow
thatpoints to the correctthis.bind
thisscope to the functionThis will bind the correct / expected
thisscope to your function. Note thatFunction.prototype.bindis ES5 and will break older browsers._.bindis a reasonable cross browser alternative.edit execute
Your passing the context as an extra parameter to execute. Then execute will call
Function.prototype.callto make sure that the function is called with the desired context