This is a very old problem, but I cannot seem to get my head around the other solutions presented here.
I have an object
function ObjA() {
var a = 1;
this.methodA = function() {
alert(a);
}
}
which is instantiated like
var myObjA = new ObjA();
Later on, I assign my methodA as a handler function in an external Javascript Framework, which invokes it using the apply(...) method.
When the external framework executes my methodA, this belongs to the framework function invoking my method.
Since I cannot change how my method is called, how do I regain access to the private variable a?
My research tells me, that closures might be what I’m looking for.
You already have a closure. When
methodAis called the access toawill work fine.Object properties are a different thing to scopes. You’re using scopes to implement something that behaves a bit like ‘private members’ in other languages, but
ais a local variable in the parent scope, and not a member ofmyObjA(private or otherwise). Having a function likemethodAretain access to the variables in its parent scope is what a ‘closure’ means.Which scopes you can access is fixed: you can always access variables in your parent scopes however you’re called back, and you can’t call a function with different scopes to those it had when it was defined.
Since
ais not a property ofthis, it doesn’t matter thatthisis not preserved when calling you back. If you do need to get the correctthisthen yes, you will need some more work, either using another closure overmyObjAitself:or using Function#bind: