Jessica Jessica - 2 months ago 8
Javascript Question

Call a returned function from outside its function

I'm trying to call a

function
that's returned from a
function
. Here's what I mean:

myFunction.something; // (Wrong)
function myFunction() {
return {
something: function() {
...
}
};
}


When I try calling
myFunction.something
nothing happens. How can I call a returned function outside of its function?

JSFiddle





var index = 0;
var animID = requestAnimationFrame(myFunction.something);

function myFunction() {
return {
something: function() {
index++;
console.log(index);
if (index === 5) cancelAnimationFrame(animID);
else animID = requestAnimationFrame(myFunction.something);
}
};
}




Answer

I would first of all recommend using descriptive variable names; utils rather than myFunction, and incrementFrame rather than something, for example. I would second of all recommend reconsidering your approach to code organization and simply putting all of your helper functions directly in an object, then referencing that object:

var index = 0;
var animID = requestAnimationFrame(utils.incrementFrame);

var utils = {
  incrementFrame: function() {
    index++;
    console.log(index);
    if (index === 5) cancelAnimationFrame(animID);
    else animID = requestAnimationFrame(utils.incrementFrame);
  }
}

There are a few differences between these approaches, some of them frustratingly subtle. The primary reason I recommend using an object for organization rather than a function which returns an object is because you don't need to use a function for organization; you are unnecessarily complicating your code.

Comments