Jump to content

self executing anonymous functions


Recommended Posts

when would you find yourself using self executing anonymous functions? I'm reading about some of the more advanced OO JS techniques but I don't see where they would be used. Is it for creating more modular JS and eliminating global variables?
The purpose of self-executing functions is to avoid pollution of the parent scope. e.g.
var a = 1;(function() { var b = (a + 1); document.write(b); })();

The variable "b" does not exist in the parent scope where "a" is declared, however, "a" exists in the scope where "b" is declared.

Edited by Dilated
Link to post
Share on other sites

Some coders use anonymous functions when they only require the function to be run from one particular location (instead of making a full, separate function out of it). There's some debate among programmers as to whether or not anonymous functions are a "proper" coding style, since they can make code a bit harder to puzzle out.

Link to post
Share on other sites

by 'one particular location' do you mean having the script placed in a certain section of your code? I don't see how anonymous functions are useful unless you put them at the bottom of your page after the DOM has loaded. Otherwise, what JS activity could you be doing if the anonymous function is in the head of your document? In the head, the DOM hasn't completely loaded so you can't manipulate or bind anything to any elements. Or am I missing something?

Link to post
Share on other sites

How many times do you need to set the onclick handler of an element? How many times does the handler repeat from one element to the next? In the common case, it would probably be once, with every handler being unique. So, as long as the element's already in the DOM, you can do:

element.onclick = function(e) {//event handler here}

Link to post
Share on other sites

It's useful when you're creating a new object and you want some form of public/private variables, which Javascript doesn't have real support for. e.g.:

some_obj = function(){  var private1 = 1;  var private2 = "two";  return ({	public1: 1,	public2: 2,	public_func: function()	{	  alert(private1);	  alert(private2);	  alert(this.public1);	  alert(this.public2);	}  });}();

Link to post
Share on other sites
How many times do you need to set the onclick handler of an element? How many times does the handler repeat from one element to the next? In the common case, it would probably be once, with every handler being unique. So, as long as the element's already in the DOM, you can do:
element.onclick = function(e) {//event handler here}

Hi boen, Thanks for the tip. When you initialize all <tag>events to a function, how do you handel passing <tag> unique parameters to the onclick event?I have
		<table bgcolor="#FF9933" id="name16" class="tablee"  frame="border">			<caption class="caption"><a rel="lightbox" href="#" onclick="expand('Pname');">Luncheon</a><span class="where">Monday-Saturday 11-3</span></caption>			<tbody bgcolor="#FFFFFF" class="dispNone" id="Pname">				<tr><th colspan="2">all with Pork Fried Rice or Steamed Rice<br />and an Egg Roll.</th></tr>				<tr><td>L 1. Beef with Broccoli</td><td class="RtJsty">$5.00</td></tr>

Where my <a tag passes a unique identifier for all of table->caption-><a tag() unique instances . In my case, the parameter sent is the unique ID of the child element, as shown above, where a table caption's <a link passes the <tbody ID. I believe there is a way to capture that child ID from the parent node list, but I'm not sure how. Thoughts?

Link to post
Share on other sites

Yo dawg, so I heard you liek Lambda?Functional Javascript this is a nice article I read a while back.You don't really set out like "omg I'm going to write this whole page anonymously!". When it becomes necessary it's used. For example when your using jQuery what do you call this?$(".btn2").click(function(){ $("p").fadeIn();});or thisvar x = function(){alert('Im in your function, doing a function.')};((alert(1)), x())or lets say you need to do a complex process to work something out just once. Why set up a whole named function etc for it when you can just govar x =( function(){return 4+3})();alert(x)

Edited by ApocalypeX
Link to post
Share on other sites

True, anonymous functions are used quite a bit. I was watching a few tutorials on Nettuts, and I saw the author doing this at the head of his page, but I could not understand why. Can you explain this? Why does he wrap the document.ready stuff in a self executing anonymous function?

(function(){   $(document).ready(function(){	  //JS here once the DOM is loaded   });})();

Link to post
Share on other sites
True, anonymous functions are used quite a bit. I was watching a few tutorials on Nettuts, and I saw the author doing this at the head of his page, but I could not understand why. Can you explain this? Why does he wrap the document.ready stuff in a self executing anonymous function?
(function(){   $(document).ready(function(){	  //JS here once the DOM is loaded   });})();

No idea, as far as I can tell, that wrapper function is redundant.
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...