If I want a function to do something different the first time it's run, I could check each time it's run to determine whether it's the first time, or I could change the function; something like this:
foo=function(a,b){
...do something1...
foo=_foo;
}
_foo=function(a,b){
...do something2...
}
Is this bad; if so, why? Is there a better way to do this? I'm specifically looking to implement this in javascript, though other language points will be considered.
This isn't a "self-modifying" function in the strict sense - you don't modify any code on the fly (and that would be bad), just assign another value to a function name. This is fine in most cases and makes polymorphic code quite simple and elegant. To make the intent cleaner, you can factor out the "first time" code into a separate function: