Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consequences of Dynamically rewriting a function in javascript?

Tags:

javascript

In javascript, you can rewrite a function, like so:

function foo() { 
   setTimeout(function() {
        alert('sup stallion');
        foo = function() { //rewrite foo to nolonger wait 4 seconds to alert.
             alert('sup stallion');
        }
   }, 4000);
}

Obviously this is a contrived example, but is there anything conceptually wrong with this approach (other than a race condition).

like image 645
Alan Avatar asked Mar 27 '12 18:03

Alan


People also ask

What is dynamic functionality in JavaScript?

The dynamic nature of JavaScript means that a function is able to not only call itself, but define itself, and even redefine itself. This is done by assigning an anonymous function to a variable that has the same name as the function.

How to create function dynamically in JavaScript?

Creating The Dynamic Function The Function object can also be used as a constructor function to create a new function on the fly. The syntax for creating a function from Function Object is as follows: const myFunction = new Function(arg1, arg2, … argN, body);


2 Answers

Self modifying code can be confusing, and hard to debug, so it's generally avoided.

Other than that there is no problem, and no race condition either.

like image 62
Guffa Avatar answered Sep 21 '22 18:09

Guffa


One thing I noticed while testing your code. Consider this:

setInterval(foo, 6000);

Function foo is being passed to setInterval before it was modified, and the original foo will run every 6 seconds, even after the binding has been updated.

On the other hand, the code below will run the original function only on the first call (which updates the binding). Subsequent calls will invoke the updated version:

setInterval(function(){foo();}, 6000);

Looks obvious, but could be hard to debug...

like image 33
bfavaretto Avatar answered Sep 23 '22 18:09

bfavaretto