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