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 some stuff
never_called_again = function (new_args) {
// Do some new stuff
}
}
Is the above valid and does it have the correct semantics? I don't want to create a new global variable with the old function name, because I'm trying to do this kind of thing not in the global scope, but from various object scopes, and I don't want name clashes when I redefine the function within those local scopes.
The "Redefinition of '{a}'" error is thrown when JSHint or ESLint encounters a variable declaration with an identifier that is the same as that of a built-in native object. In the following example we attempt to declare a variable with the identifier String : var String = "My String"; x. 1.
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
No, it's not possible.
functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.
It is indeed possible to redefine a function from its body. The technique is used in the so-called Lazy Function Definition Pattern.
It looks like this:
// Lazy Function Definition Pattern
var foo = function() {
var t = new Date();
foo = function() {
return t;
};
return foo();
}
This function stores the Date of the first call, and returns this Date afterwards.
If you compare this with the module pattern, the difference is that the initialization only happens when it's first called, not when it's defined. For costly initializations it can be a huge benefit.
// Conditional Module Pattern
var foo = (function() {
var t;
return function() {
if (t) {
return t;
}
t = new Date();
return t;
}
})();
Yes, you can redefine a function that way.
Running This:
function never_called_again(args) {
console.log('Func 1', args);
never_called_again = function (new_args, x) {
console.log('Func 2', new_args, x);
}
}
never_called_again('arg A', 'arg B');
never_called_again('arg A', 'arg B');
Yields this:
Func 1 arg A
Func 2 arg A arg B
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