1
的範圍我理解的「這個」特別是嵌套代碼回調嵌套,這
這裏時,我有
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');
});
});
}
問題的例子,我甚至嘗試綁定
範圍問題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');
});
});
}
當我試圖用我這點這裏面的代碼..它的工作.. 我能理解這裏發生了什麼,因爲我不明白這一點
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');
});
});
}
有沒有更好的方法來做到這一點或確定回調的範圍?任何建議
JavaScript中的'this'與其他語言不同。具體來說,所有函數都有'this',而不僅僅是方法。所以如果你嵌套函數,那麼嵌套函數中的'this'來自'function(){}'而不是'MyClass'。下面是一個解釋「this'如何工作的答案:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628? = 1 | 3.8887#13441628 – slebetman