Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    May 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Javascript function question

    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

    (function(){

    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?

    Thanks
    Goddball

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Posts
    1,404
    Thanks
    2
    Thanked 32 Times in 32 Posts
    It is a function literal.

    Would need to see more to get the context.

    http://docstore.mik.ua/orelly/webpro...pt/ch07_01.htm

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,373
    Thanks
    11
    Thanked 592 Times in 572 Posts
    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:
    Code:
    n=1+2+3;
    is the same thing as
    Code:
    n=(function(){return 3+2+1;}());
    Last edited by rnd me; 05-15-2009 at 05:52 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    New to the CF scene
    Join Date
    May 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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
    */
    (function(){

    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.

    Goddball

  • #5
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    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.
    Code:
    <HTML>
    <HEAD>
    <TITLE></TITLE>
    
    <script language="JavaScript">
    
    </script>
    <script src="http://stirfrydesign.110mb.com/javascript/wiiscroll.js"></script>
    <script src="excanvas.js"></script>
    
    </HEAD>
    
    <BODY >
    <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 ()
    
    (n);
    
    //now just the n
    
    n;
    
    //now just an alert wrapped in ()
    
    (alert(3+2+1))
    
    //but wait, just an alert does the same thing
    
    alert(3+2+1);
    
    </script>
    
    </BODY>
    
    </HTML>
    All the same thing!!
    Last edited by TinyScript; 05-15-2009 at 07:54 PM.

  • #6
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    I have an example of a Jquery script that I removed from the j zone.
    here's the original.
    http://matarillo.com/blogdata/kkc2/

    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.
    Code:
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" >
            <title>Kuru Kuru CAPTCHA 2</title>
            
        </head>
        <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;
    //alert(sdx+""+sdy)
                    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.rotate(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};
                
            }
    
    
            </script>
            <input value="send" onclick="alert('Angle in radians ' + img.rad + '!!')" type="button" />
        </body>
    </html>
    I'm trying figure out position, so I use the address bar
    Code:
    javascript:void(0);alert(canvas.position)
    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"
    Code:
    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;
    }
    Last edited by TinyScript; 05-15-2009 at 10:22 PM.

  • #7
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,373
    Thanks
    11
    Thanked 592 Times in 572 Posts
    without the assignment, it is just a legitimate statement.

    consider:
    Code:
    var x=1;
    "hello world";
    x=x+1;
    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.

    [CODE]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:
    Code:
    
    r=[1,2,3,4];
    sum=0;
    for(i=0, mx=r.length;i<mx;i++){
      var sum2=Number(sum);
      setTimeout(function(){alert("from loop:"+sum2);}, 200 * i);
      sum+=i;
    }
    
    
    
    
    sum=0;
    r.map(function(a,n){
        var sum2=Number(sum);
        setTimeout( function(){alert("from map:"+sum2);}, 200 * n);
        sum+=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.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •