View Full Version : Javascript function question

05-15-2009, 03:19 AM
I have a basic question on Javascript functions which hopefully is not too dumb. In looking at the Jquery library I see that the first line of executable code starts out as


My problem is that in none of the Javascript books I have does this construct appear. There is no name for this function and the closest I thing I can find is a function literal but that doesn't seem to be what's happening here. I don't understand the purpose of the initial para but I assume it is an essential part of the construct somehow.

Can anyone explain exactly how this construct works or provide a reference?


05-15-2009, 03:30 AM
It is a function literal.

Would need to see more to get the context.


rnd me
05-15-2009, 06:47 AM
it is not a function literal in practice.

it's an anonymous function, the parens give it away.

sometimes you'll see function literals referred to as anonymous functions, but they are really just function expressions, not anons.

basically, anons give you a new scope, so you can use good var names without conflicting with or creating globals, package scope for later via closure, or fit a couple lines of code into a spot where a simple value would normally go.

one great thing about js is that you can use an anon anywhere you would normally use an expression, assignment, or variable.

for example:

is the same thing as

n=(function(){return 3+2+1;}());

05-15-2009, 07:16 PM
Thanks for the replies but I have to admit I'm still a little confused. The confusion results from the examples provided by the Javascript books I have and these replies.

All the examples seem to have an assignment operator, so to take "rnd me"'s example the anonymous function is

n=(function(){return 3+2+1;}());

but what happens if the n= part is missing? That is what if you only have

(function(){return 3+2+1;}());

does this get executed immediately when loaded?

I have the same problem with considering the construct as part of a function literal. There is no assignment.

For reference the actual code (truncated) is

* jQuery JavaScript Library v1.3.2
* http://jquery.com/
* Copyright (c) 2009 John Resig
* Dual licensed under the MIT and GPL licenses.
* http://docs.jquery.com/License
* Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
* Revision: 6246

bunch of initialization stuff here

As you can see the first executable statement doesn't have an assignment operator so there is no way I can see to reference the function. If the code gets excuted when the script is loaded it then makes some sense since all this particular function seems to do is initialize other variables and functions but it does look a little strange and I'm not sure that this is the correct interpretation.


05-15-2009, 08:36 PM
Good questions that I needed to answer for myself as well. I'm in the process of understanding why they are used and when they are not needed. in this case, it runs only once and that's it. You can't call it again unless you reload the page. if it was in a function, it would only run once every time.
This is how I understood the purpose. It's to save writing the name of the function that only runs once anyway, so there is no need to name it.


<script language="JavaScript">

<script src="http://stirfrydesign.110mb.com/javascript/wiiscroll.js"></script>
<script src="excanvas.js"></script>



n=(function(){return alert(3+2+1);}());

//but what happens if the n= part is missing?

(function(){return alert(3+2+1);}());

//how about n wrapped in ()


//now just the n


//now just an alert wrapped in ()


//but wait, just an alert does the same thing




All the same thing!!

05-15-2009, 11:08 PM
I have an example of a Jquery script that I removed from the j zone.
here's the original.

and here's my test version. I needed to understand how and what Jquery was doing, so this was a cool script to disect. It's not correct because I never figured out the positioning, but the image at least rotates. I keep trying to find a solution for this. Maybe one of the smart coders here knows how to correct the rotation speed and the position() alternative, which is a Jquery function apparently.

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" >
<title>Kuru Kuru CAPTCHA 2</title>

<body onload="run()">
<h1>Welcome to Kuru Kuru CAPTCHA 2!</h1>

<canvas width="250" height="250" id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var img = new Image;
img.src = 'http://i41.tinypic.com/3486rl5.png';
img.rad = 0.0;
img.drag = false;
var canvasX = canvas.offsetLeft;
var canvasY = canvas.offsetTop;
img.ox = 100
img.oy = 100
function run(){
ctx.translate(100, 100);
ctx.drawImage(img, -100, -100, 200, 200);
canvas.style.cursor= 'pointer';
canvas.onmousedown=function(event) {
img.drag = true;
img.sx = event.clientX;
img.sy = event.clientY;};
canvas.onmousemove=function(event) { if (!img.drag) return;
var sdx = img.sx - img.ox ;
var sdy = img.sy - img.oy;
var srad = Math.atan2(sdy, sdx);
var cdx = event.clientX - img.ox ;
var cdy = event.clientY - img.oy ;
var crad = Math.atan2(cdy, cdx);
var rad = crad - srad;
img.dr = rad;
ctx.drawImage(img, -100, -100, 200, 200);};
canvas.onmouseup=function(event) {img.done();};
canvas.onmouseout=function(event) {img.done();};

img.done = function() { if (!img.drag) return;
img.drag = false;
var rad = img.rad + img.dr;
if (rad > Math.PI) rad -= (2 * Math.PI);
if (rad < -Math.PI) rad += (2 * Math.PI);
img.rad = rad};


<input value="send" onclick="alert('Angle in radians ' + img.rad + '!!')" type="button" />

I'm trying figure out position, so I use the address bar


and get this
Can anyone versed in the Jquery help me understand what it's doing. It's like learning a whole new language just to figure out what is what. I know it's clever and all, but creating an instance of the canvas and passing some variables shouldn't take a whole library. Is my version prone to conflicting with other scripts? Is that the advantage of using Jquery? I hope someone can help answer these questions. I really want to "WANT TO USE" Jquery, but it's simply easier to create my own scripts than deal with "writing less to do more"

function () {
var I = 0, H = 0, F;
if (this[0]) {
var G = this.offsetParent(), J = this.offset(), E = /^body|html$/i.test(G[0].tagName) ? {top: 0, left: 0} : G.offset();
J.top -= j(this, "marginTop");
J.left -= j(this, "marginLeft");
E.top += j(G, "borderTopWidth");
E.left += j(G, "borderLeftWidth");
F = {top: J.top - E.top, left: J.left - E.left};
return F;

rnd me
05-16-2009, 08:56 AM
without the assignment, it is just a legitimate statement.


var x=1;
"hello world";
alert(x)//shows 2

the string in the middle is the same idea. it's non-accessible later, but it's not invalid either.

the contents of an anonymous function are executes whenever the function in encountered. if it's just in the body of a script, then it fires immediately, inline, just as "global code" would.

functions (regular,names,anon, constructors, or expressions) are the only construct in javascript that have true scope. this scope in inherited by a function from it's enclosing environment, be it global (if in the script body), or from another function around it.

the anon function is often used so that a library maker can use good names.

for example, var body=document.body; and not have that conflict with a variable you created named body that holds the string body of an email.
it gives you read-only access to the outside world, so long as var statements are used inside the anon. you won't step on anyone's variables that way, so it reduce conflicts substantially.

if you want block scope in loops, use a functional approach instead of a block statement.

consider the following:

for(i=0, mx=r.length;i<mx;i++){
var sum2=Number(sum);
setTimeout(function(){alert("from loop:"+sum2);}, 200 * i);

var sum2=Number(sum);
setTimeout( function(){alert("from map:"+sum2);}, 200 * n);

the loop value is not enclosed, but the map version encloses sum2 because it occurs inside of another function: the function literal used in the map code. This in turn is available to the timeout's function, and so the number starts to increment.

it's not the best demo, but it shows the concept at work.