我不知道如何最好地解释这个问题,因为有很多事情要做,所以我继续创建了一个我正在做的事情的样本。下面是代码:
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
在该函数内部未定义。关于为什么以及如何修复它以便我可以访问变量并最好保留代码架构的任何想法?
提前致谢。