我在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
。
如何通过引用发送函数的对象将函数传递给对象?