Ahmad Ahmad - 1 year ago 62
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
that has a public variable (an instance of
class) which is a Finite State Machine model to control the action of the player.

The AI instance
is responsible for calling whichever function that is passed to it by the owner
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
in that function gets evaluated to

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download