Ad

Is It Possible To "assign" A Function To Another Function?

I'm pretty new to coding and I'm looking for advice.

I'm having a set of functions inside an animation loop that are executed depending on a variable value. This means I'm actually checking the value each frame and execute the associated function.

Since the value of the variable only changes on user input, I was thinking about taking the if else - statement out of the animation loop. I was wondering if I could "assign" the associated function to another function that runs in the loop but is able to change its content.

Any thoughts on this? :-)

Ad

Answer

Functions in JavaScript are objects. That means variables can refer to functions.¹

So if you have functions a, b, and c, you can have a current variable referring to the one you're currently using, for instance, a:

let current = a;

Later, if things change, you can update current to refer to b instead:

current = b;

Either way, you then use current exactly like you'd use a or b:

current(/*arguments go here if any*/);

Live Example:

const btnCall = document.getElementById("btnCall");
let current;

useA();

function a() {
    console.log("Function `a` called");
}

function b() {
    console.log("Function `b` called");
}

function useA() {
    current = a;
    btnCall.value = "Call a";
}

function useB() {
    current = b;
    btnCall.value = "Call b";
}

hook("btnCall", () => {
    current();
});
hook("btnUseA", useA);
hook("btnUseB", useB);

function hook(id, fn) {
    document.getElementById(id).addEventListener("click", fn);
}
<input type="button" value="Call ?" id="btnCall">
<input type="button" value="Use a" id="btnUseA">
<input type="button" value="Use b" id="btnUseB">

Also on CodePen (snippets are down for a lot of people right now).


¹ In fact, any time you're not using an object property to refer to a function, you're always using a "variable" (more accurately, a binding) to refer to a function. When you do:

function example() {
}

...you're creating a function and a variable in the current scope that refers to the function. The variable created by a function declaration like that is effectively identical to a var variable. Variables (var, let), constants (const), and function parameters are all bindings that hold values, including references to objects such as functions.

Ad
source: stackoverflow.com
Ad