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).
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.
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);
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With