我在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对象调用的动作函数的定义没有对传递该函数的对象的任何引用,因此,该函数中对this的任何引用都将被计算为undefined。
如何通过引用发送函数的对象将函数传递给对象?
发布于 2016-11-16 15:09:41
使用.bind()在调用时设置函数的上下文(this)。例如:this.brain.setAction(idle.bind(this))
https://stackoverflow.com/questions/40635495
复制相似问题