Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting functions in java scripts

Tags:

javascript

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/

like image 899
GoodSp33d Avatar asked Jun 06 '13 18:06

GoodSp33d


People also ask

Can function be redefined?

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.

How to create dynamic function in JavaScript?

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);

Can you return a function in JavaScript?

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.

What is a dynamic function in JavaScript?

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.


1 Answers

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 ];
}
like image 146
aggsol Avatar answered Sep 19 '22 19:09

aggsol