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 finishes
BAD
<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 it
GOOD
<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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s