I have a problem understanding the scope of 'this' especially when nesting code
here is the example that I have a problem with
var callbacks = [];
MyClass.protoype.CallServer = function(name,index,callback)
{
//some code
callbacks[callback.length] = callback;
callserverfor(name,index, callbacks.length-1);
}
MyClass.prototype.ReceiveFromServer = function(callbackId,param)
{
//somecode for simplicity let's say
if(param)
callbacks[callbackId].call(param);
else
callbacks[callbackId].call();
}
MyClass.prototype.Connect(Index,callback)
{
CallServer('Connect' , Index, callback);
}
MyClass.prototype.Start= function(Index)
{
this.Connect(Index,function()
{
this.ISConnected = true;
//HERE this lost scope
this.GetIdentified(Index, function( Identifier)
{
alert('Identifier');
});
});
}
I even tried bind
MyClass.prototype.ReceiveFromServer = function(callbackId,param)
{
//somecode for simplicity let's say
if(param)
callbacks[callbackId].call(param);
else
callbacks[callbackId].call();
}
MyClass.prototype.Connect(Index,callback)
{
CallServer('Connect' , Index, callback);
}
MyClass.prototype.Start= function(Index)
{
this.Connect(Index,function()
{
this.ISConnected = true;
var GetIdentifier = this.GetIdentifier;
GetIdentifier.bind(this);
//HERE this lost scope
this.GetIdentifier(Index, function( Identifier)
{
alert('Identifier');
});
});
}
When I tried to use Me which point to this inside the code .. it worked .. Can I understand what is happening here as I don't get it
MyClass.prototype.ReceiveFromServer = function(callbackId,param)
{
//somecode for simplicity let's say
if(param)
callbacks[callbackId].call(param);
else
callbacks[callbackId].call();
}
MyClass.prototype.Connect(Index,callback)
{
CallServer('Connect' , Index, callback);
}
MyClass.prototype.Start= function(Index)
{
var Me= this;
this.Connect(Index,function()
{
Me.ISConnected = true;
//HERE this lost scope
Me.GetIdentifier(Index, function( Identifier)
{
alert('Identifier');
});
});
}
Is there a better way of doing this or determining the scope of the callback ? any suggestions