0

Is it possible to insert new actions inside the scope of a function from outside? For example:

       function main(){
           //I want to insert in here new action to perform
       }

       var dosomething = function() { 
             console.log("I want to be inside the main");
       }

       main();

How do I make the function main permanently execute the function dosomething? And after that, how can I take out the function dosomething from the main?
The concept is more or less this:

    function main(){
           //I want to insert in here new actions to perform
    }

    var dosomething = function() { 
             console.log("I want to be inside the main");
    }


   *insert dosomething in main*

   //This is how it should look now the function main:
   function main(){
          dosomething();
   }


   *erase dosomething from main*

   //The function main come back to be empty:
   function main(){
   }

The only solution I found is to make the function main execute all the functions inside an array and use this array to insert/take-out functions from outside. Is there any better solution?

TTK
  • 223
  • 6
  • 21
  • 1
    I suspect this is the X/Y problem: You need to solve X, and you think Y (inserting and removing functionality inside an existing functon) is the way to do it, but more likely there's a better solution for X than that. – T.J. Crowder Apr 03 '15 at 10:28
  • Maybe have a look at [here](http://stackoverflow.com/q/24911700/1048572) – Bergi Apr 03 '15 at 10:29
  • @Crowder: I don't know, basically I would like to use this technique to simply add and remove animations inside this loop: `function main(){ window.requestAnimationFrame(main); }` – TTK Apr 03 '15 at 10:51
  • @TTK: For that, an array is the perfectly legitimate solution. – Bergi Apr 04 '15 at 21:45

1 Answers1

0

How do I make the function main permanently execute the function dosomething?

You could decorate it, like

var oldmain = main;
main = function() {
    doSomething();
    return oldmain.apply(this, arguments);
}

And after that, how can I take out the function dosomething from the main?

No, you cannot. Functions are immutable objects in that regard, which cannot be decomposed. The only thing you can do is to take oldmain again.

I would like to use this technique to simply add and remove animations inside this loop:

function main(){ window.requestAnimationFrame(main); }

The only solution I found is to make the function main execute all the functions inside an array and use this array to insert/take-out functions from outside.

For an animation of dynamic size this is a perfect solution. Nothing wrong with it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375