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在该函数内部未定义。关于为什么以及如何修复它以便我可以访问变量并最好保留代码架构的任何想法?

提前致谢。

4

1 回答 1

5

调用函数function时的作用域与Class对象的作用域不同。这意味着“this”指的是别的东西:

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';



 //generic function that handles all actions
     this.handleAction = function(action){
    try{
      //you are calling the function in another scope
      this.actions[action]();
    }catch(err)
    {
      document.write("Error doing "+action);
    }
  };
}

相反,您可以这样做:

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(color);
  };


  //sample class variable
  //this way it's available to all inside functions
  var color = 'red';
}

虽然这不是一个简单的章节,但我建议您了解更多关于 javascript 作用域和 clojures 的信息。

基本上你需要从这里学到的是,当你在没有任何先前上下文的情况下调用一个函数时,它不能依赖“this”。这就是为什么可以使用以下方法更改方法调用的上下文的原因.call(context,args..)

例子:

function Class()
{
  //we store the context
  var scope=this;
  //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{
      //we call our function in the Class context
      this.actions[action].call(scope);
    }catch(err)
    {
      document.write("Error doing "+action);
    }
 };
}
var cl = new Class();
cl.handleAction("triggerScream");
cl.handleAction("triggerDisplay");
于 2012-07-30T21:43:14.187 回答