简体   繁体   中英

Memory consumption by anonymous function in javascript

As soon as the function is declared wth function keyword javascript assigns a block of memory to the function name where function itself gets stored.

function maiz(){}
console.log(maiz);//output:function maiz(){}

but what will js do when function is declared anonymous or where will the anonymous function gets stored

(function (){})()

As soon as function is declared there should be some memory to store even the annonymos function and than execute it.Am i wrong?

You cannot declare an anonymous function. What you can do is have an anonymous function expression , which means you feed the function object somewhere (assignment, function call argument, etc). See Kangax' article or this question for the difference.

So if you want to know where an anonymous function expression goes to (in the memory), you will have to look at the surrounding statements. This one for example:

 (function (){});

would immediately after it has been instantiated be vanished by the garbage collector. And if you have

 (function (){})();

then the code inside will be executed (in a new scope), but the function itself will not get stored anywhere as well. Btw, this construct is called an immediately-invoked function expression (IIFE) .

Anonymous functions are better explained in the book Secrets of the JavaScript Ninja (John Resig)

We can declare an anonymous function as a property of an object.

var ninja = {
    shout: function(){ // shout property now referenced to anonymous function 
        assert(true,"Ninja");
    }
};

Anonymous functions are typically used in cases where we wish to create a function for later use, such as storing it in a variable, establishing it as a method of an object, or using it as a callback (for example, as a timeout or event handler). In all of these situations, the function doesn't need to have a name for later reference.

If there's no need for a function to be referenced by its name, we don't have to give it one (Anonymous function). It behaves as actual function which has name. But it doesn't have name. So Anonymous functions are stored where javascript functions are stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM