Just came across a funky function rewriting concept in Javascript.
var foo = function () {
alert("Hello");
foo = function () {alert("World !");};
};
foo();
foo();
In what situations are these helpfull and is there any other scripting language which support this kind of code ?
Fiddler link : http://jsfiddle.net/4t2Bh/
It is indeed possible to redefine a function from its body. The technique is used in the so-called Lazy Function Definition Pattern. This function stores the Date of the first call, and returns this Date afterwards.
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);
Functions are the same data as numbers or strings, so functions can be passed to other functions as arguments, as well as returned from functions. We can even define a function inside another function and return it outside.
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.
You can use this idiom to initialize a LUT on the first call like this
var getBase32Value = function (dummy) {
var base32Lut = {};
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
for(var i=0; i<alphabet.length; i+=1) {
base32Lut[ alphabet[i] ] = i;
}
getBase32Value = function (v) {
return base32Lut[ v ];
}
return base32Lut[ dummy ];
}
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