Ahmad Ahmad - 21 days ago 5
Javascript Question

How can I pass a function that has a reference to the object which passed the function in Javascript

I have the following "class" function in 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
}
}


===

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
}
}


I am basically having an instance of
Player
that has a public variable (an instance of
AI
class) which is a Finite State Machine model to control the action of the player.

The AI instance
brain
is responsible for calling whichever function that is passed to it by the owner
player
object. The function is passed correctly to the AI class, however, the definition of the action function once called by the AI object does not have any reference to the object which passed the function, and so, any reference to
this
in that function gets evaluated to
undefined
.

How can I pass a function to an object with a reference to the object which sent the function?

Answer

Use .bind() to set the context (this) of a function at call time. For example: this.brain.setAction(idle.bind(this))