Function pointers in JavaScript?

I thought JS could do function pointers?

I want to do my Player character’s finite state machine using dynamic dispatch. So the guts of the Player script would be:

var state = idle;

function Update() {
    state();
}

Where state is a function pointer. Then I would have various functions like this:

function idle() {
    applyMotion();
    var h = Input.GetAxis("Horizontal");
    var v = Input.GetAxis("Vertical");
    if (v != 0) {
        state = walk;
	animation.CrossFade("walk", 0.02);
    } else if (h != 0) {
        state = sidestep;
        animation.CrossFade("sidestep");	
    }
}

function walk() {
    // and so on
}

function sidestep() {
    // and so on
}

Eg, each “state” function can reset the state variable.

Doesn’t work though, as my Update() method throws an IllegalCastException when trying to use “InvokeCallable”.

Anyone know what that means? Is it possible to use JavaScript function pointers inside Unity?

As idle, walk and sidestep are methods and not functions, you will have to pass the current instance explicitly when invoking them through a reference.

I beleive it is done simply by passing this as the first parameter the function reference:

function Update() {
    state(this);
}