Is it possible to redefine a JavaScript function from within its own body. For example, could I do the following?
function never_called_again(args) {
// Do
Strictly speaking, no, it isn't possible to redefine a JavaScript function at all. Though it's kind of a matter of semantics.
A function may overwrite its reference within a certain scope with another function, which serves as a sleight of hand where another function appears in the place of the first. e.g.
greet_once = function() {
console.log('Hello.');
greet_once = function() { console.log('Can I help you?') };
};
Similarly a function may use the state of a closured scope to behave differently the second time its called (obviously not "redefinition").
The following example illustrates why the above pattern isn't redefinition because it depends on the parent scope which may not be shared with the calling scope.
greet_always = function() {
greet_once = function() {
console.log('Hello.')
greet_once = function() { console.log('Can I help you?') }
};
return greet_once()
}()
greet_always()
greet_always()
The function being called as greet_always (which always prints 'Hello.') is the same one, assigned originally to greet_once.
The closest I believe you can get to redefining a function is to reassign its apply and call methods, which produces a scenario where myFunction.call() is different from myFunction(), which is weird but conceivably useful.