Software , Photography & more …

Menu

self invoking anonymous function expression

So usually in writing JavaScrip in any website , things get missy and memory consumption gets nasty and a lot of time spent on profiling and debugging why the JavaScript gets so slow one of the reasons i found making writing JavaScript is that any thing can work , just place a script tag and write whatever you want and it will work
So i want to give you an example of writing a better JavaScript that can make your JavaScript run with better performance and this is called “Self Infoking anonymous function excepression” or in other words encapsulating your code which is written in various JavaScript files , so every one off them will be in it’s own temporarily scop and will be destructed once the execution finishesBAD
<script type=”text/javascript”>
var showAlert = function(){
alert(x);
};
</script>

What this code means that your showAlert function is exposed to the global namespace level which in meny cases does not have logical meaning unless you are having this as a utility function and want to expose itGOOD
<script type=”text/javascript”>
(function(){
var showAlert = function(){
alert(x);
})();
</script>

Now you have this anonymous function that will be self invoked and it will have it’s own scoop so your showAlert function wont be exposed to the Global namespace