首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何传递具有对Javascript中传递函数的对象的引用的函数?

如何传递具有对Javascript中传递函数的对象的引用的函数?
EN

Stack Overflow用户
提问于 2016-11-16 15:07:05
回答 1查看 45关注 0票数 0

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

代码语言:javascript
复制
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
  }
}

===

代码语言:javascript
复制
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对象调用的动作函数的定义没有对传递该函数的对象的任何引用,因此,该函数中对this的任何引用都将被计算为undefined

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-16 15:09:41

使用.bind()在调用时设置函数的上下文(this)。例如:this.brain.setAction(idle.bind(this))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40635495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档