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/
asked Jun 6, 2013 at 18:49
GoodSp33d
6,3024 gold badges37 silver badges70 bronze badges
1 Answer 1
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 ];
}
answered Jun 7, 2013 at 9:31
aggsol
2,5771 gold badge39 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
foo()a second time and see the alert says. It will not be hello.if(!ran){ran=true; ...}) than this self-rewriting code.