Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Javascript: Assigning anonymous functions to attributes

  1. Apr 20, 2016 #1
    I have the following code creating an object on a web page:
    My question is if the
    Code (Javascript):
            function(event)
            {
                // var id=myid;
                unbind(event, this);
            }
    part of the code below results in a unique instantiated function per anchor or will all anchors point to the same anonymous function and only one object is instantiated for all used anchors. How does the interpreter handle break points on this line of code?


    Does this change when I remove the // from the commented out line in the example?


    Code (Javascript):
    function createElements()
    {
        createElemA('first', 'jsfirst',
            function(event, obj)
            {
                ... do something to handle the click of first
            }
        );
        createElemA('second', 'jssecond',
            function(event, obj)
            {
                ... do something to handle the click of second
            }
        );
    }


    function createElemA(myid, myjsid, unbind)
    {
        memberElemA1=$("<a href='#' class='close unbind' id='" + myid + "' jsid='" + myjsid + "'>&times;</a>");
        memberElemA1.click(
            function(event)
            {
                // var id=myid;
                unbind(event, this);
            }
        );
    }
     
  2. jcsd
  3. Apr 20, 2016 #2
    Logically I would say the function stops existing after the calling function has run it's course.
    Sometimes those kind of functions are called lambda functions.

    What you might find interesting is http://markdalgleish.com/2011/03/self-executing-anonymous-functions/
    This isn't exactly the same but can help getting a grasp of anonymous functions and how to test their scope.

    About uncommenting
    Code (Javascript):

    var id = myid;
     
    It is local so when you are outside the scope of the anonymous function it doesn't exist (with that value, you can have a global variable id).
    The keyword is scope, it tells you which functions, variables and whatnot are available.
    A quick scan of http://stackoverflow.com/questions/17139445/javascript-lambda-functions seems to answer some of the questions you have.
     
  4. Apr 20, 2016 #3
    Thank you Joris,

    I just wanted to point out that the anonymous function is placed in the list of onclick handlers of the anchor which means that the function would have to remain as long as the anchor exists or if the click event list is not cleared.
    I expect the
    Code (Javascript):
    var id = myid;
    to be added to the scope of the anonymous function but when called I cannot tell what myid would be as it is not active anymore.
     
  5. Apr 20, 2016 #4
    It can only be used when inside the function.
    Even if the function exists, the variable gets "cleaned up" when you reach the final brace closing the function.

    What you basically have is that you associate an action with the "onClick" event for a certain element.
    The function only gets called when the event happens, I don't know if the function is cached or looked up every time (I suspect the first).
    An instance of the function only exists after you clicked and gets killed after the function is done (unless I'm overlooking something which is quite possible with JS)

    tl;dr
    Whenever you click, a new 'instance' of the function is called.
     
  6. Apr 20, 2016 #5
    The keyword is "closure". It's explained here in detail
    http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    The short answer is every time "createElemA" is called, a new instance of your function is created and registered as an event handler. That function instance is actually a kind of object and subject to the same garbage collection rules as any other object.
    So if you have code like this in your program
    Code (Javascript):
    var f = function(x) {
      //some code
    };
    every time that code is executed a new function object is created.
    btw. if you write
    Code (Javascript):
    function f(x) {
      //some code
    }
    That's really just syntactic sugar for my first example.
    If you uncomment the line "var id=myid;" then a reference to the current instance of myid - in many languages that is called the local stack frame - will be stored in the function object. That means that myid is not being cleaned up. It can't be since there still exists a reference to it.
    That's not quite correct. Clicking the element causes the function to be executed. But no new instance is created.
     
  7. Apr 21, 2016 #6
    Thanks DrZoidberg, I didn't know it was called Closure. It does makes a lot more sense now.
    All objects are being kept 'alive' even though the object's method has run its course. Reference counting will keep these things alive and as you mention all within Javascript is actually an object (with a few exceptions).
    It also tells me that spawning large amounts of entangled code that is called recursively will not make a happy programmer and/or a happy garbage collector.
    One of the reasons I asked this was because some of the page's javascript instances were unusually large, normally only 800kb on average but the ones where we had large lists and many dependencies within the lists to other objects on the page the instance grew to 20-50Mb at times.
    I can see a good way to avoid this in the future and be more weary of what is done in anonymous functions.

    As to quote the great Scott:
    Oh, what a tangled web we weave
    When first we practise to deceive!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Javascript: Assigning anonymous functions to attributes
  1. Javascript problem (Replies: 6)

Loading...