9

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/

7
  • 1
    This is called lazy function definition, similar to lazy loading except that the variable happens to hold a function. Commented Jun 6, 2013 at 18:53
  • That just gives you a warning that variable is already defined and will just alert "Hello" jsbin.com/ocezar/1/edit Commented Jun 6, 2013 at 18:55
  • 1
    @elclanrs but call foo() a second time and see the alert says. It will not be hello. Commented Jun 6, 2013 at 18:58
  • 3
    It is helpful if you need to run a expensive lookup/check that will not change and you can make it so the following calls use the previously found data. Sort of like a getter type of pattern. jsfiddle.net/NHHFH Commented Jun 6, 2013 at 19:00
  • I'd rather see a one-shot flag (if(!ran){ran=true; ...}) than this self-rewriting code. Commented Jun 6, 2013 at 19:17

1 Answer 1

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 ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.