Javascript: Assigning anonymous functions to attributes

  • Java
  • Thread starter Michael27
  • Start date
  • #1
24
3
I have the following code creating an object on a web page:
My question is if the
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?


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);
        }
    );
}
 

Answers and Replies

  • #2
489
189
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
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.
 
  • #3
24
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
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.
 
  • #4
489
189
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.
 
  • #5
521
70
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
JavaScript:
var f = function(x) {
  //some code
};
every time that code is executed a new function object is created.
btw. if you write
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.
Whenever you click, a new 'instance' of the function is called.
That's not quite correct. Clicking the element causes the function to be executed. But no new instance is created.
 
  • Like
Likes Michael27
  • #6
24
3
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!
 

Related Threads on Javascript: Assigning anonymous functions to attributes

Replies
2
Views
1K
  • Last Post
Replies
1
Views
1K
Replies
3
Views
1K
Replies
13
Views
4K
  • Last Post
Replies
3
Views
3K
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
11
Views
3K
Replies
9
Views
904
Top