1
由於有很多事情要做,所以我不知道如何最好地解釋問題,所以我繼續創建了一個樣本我在做什麼。下面是代碼:無法在特定情況下從類的函數內訪問類的變量
var cl = new Class();
cl.handleAction("triggerScream");
cl.handleAction('triggerDisplay');
function Class()
{
//function which will print static string
this.scream = function(){
document.write("AAAAAAA!!!<br/>");
}
//function which will print the class variable
this.display = function(){
document.write(this.color);
};
//sample class variable
this.color = 'red';
//map of actions
this.actions = {
'triggerDisplay' : this.display,
'triggerScream' : this.scream
};
//generic function that handles all actions
this.handleAction = function(action){
try{
this.actions[action]();
}catch(err)
{
document.write("Error doing "+action);
}
};
}
而這裏的jsbin鏈接:http://jsbin.com/etimer/2/edit
在摘要,有一個handleAction()
功能,它可以處理各種事件和喚起等功能完成的事件。爲此,我有了動作事件和功能的地圖。函數display()
訪問類變量,但由於某種原因,this
在該函數內部未定義。任何想法,爲什麼以及如何解決它,以便我可以訪問變量,並最好保持代碼架構?
在此先感謝。
這正是我一直在猜測的問題的原因。由於函數的重新分配很多,因此很難跟蹤範圍。我會嘗試這個解決方案。謝謝! – Sherzod 2012-07-30 21:57:07