如何传递一个函数,该函数具有对在Javascript中传递函数的对象的引用

时间:2016-11-16 15:07:06

标签: javascript

我在javascript中有以下“class”函数:

function AI() {   
   // this class is responsible for managing AI behavior

   var action;    // this is a private variable 
                  // that will be used to point to a function

  this.setAction = function(an_action) {
       action = an_action;     //this function will receive reference 
  }                            // to another function ( an_action() )

  this.update = function() {
      action();                 // this line will execute the passed-in function
  }
}

===

function Player() {
    this.x = 100;
    this.y = 200;
    ...
    this.brain = new AI();   // an instance of AI class to manage Player actions

    this.brain.setAction(idle);  // idle is a function defined below
    ...
    this.update = function() {
       // here we might move the player's location (x,y)
       this.brain.update();   // this line will call the current (action) 
                              // which is a reference to idle function

    }

   this.draw = function() {
       // here I will draw the player at x,y
   }

   function idel() {
      this.xSpeed = 0;   // the player does not move
      ...

   }

   function jump() {
     this.y += 4;   // or any logic that makes the player jump
     ...            // 
     this.brain.setAction(idle);   //after jumping is done, go back to idle
   }
}

我基本上有一个Player的实例,它有一个公共变量(AI类的实例),它是一个控制播放器动作的有限状态机模型。

AI实例brain负责调用所有者player对象传递给它的任何函数。函数正确传递给AI类,但是,AI对象调用的action函数的定义没有对传递函数的对象的任何引用,因此,对this的任何引用都是函数被评估为undefined

如何通过引用发送函数的对象将函数传递给对象?

1 个答案:

答案 0 :(得分:1)

使用.bind()在通话时设置功能的上下文(this)。例如:this.brain.setAction(idle.bind(this))