Javascript: Assigning anonymous functions to attributes

  • Context: Java 
  • Thread starter Thread starter Michael27
  • Start date Start date
  • Tags Tags
    Functions Javascript
Click For Summary

Discussion Overview

The discussion revolves around the behavior of anonymous functions in JavaScript, particularly in the context of event handling and scope. Participants explore how these functions are instantiated, their lifecycle, and the implications of using variables within them.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant questions whether the anonymous function assigned to an anchor's click event results in unique instances for each anchor or if they all reference the same function.
  • Another participant suggests that anonymous functions, sometimes referred to as lambda functions, cease to exist after their containing function completes execution.
  • A different viewpoint emphasizes that the anonymous function remains as long as the associated anchor exists and that the variable scope is crucial for understanding its behavior.
  • One participant asserts that the variable defined within the anonymous function is cleaned up after the function execution, raising questions about its availability post-execution.
  • Another participant introduces the concept of closures, explaining that a new instance of the function is created each time the containing function is called, and that these instances are subject to garbage collection rules.
  • There is a discussion about the implications of uncommenting a line of code that assigns a variable within the function, suggesting it would retain a reference to the variable beyond its immediate scope.
  • One participant expresses concern about the memory usage of JavaScript instances when dealing with large amounts of entangled code and dependencies, indicating a potential performance issue.

Areas of Agreement / Disagreement

Participants express differing views on the lifecycle of anonymous functions and the implications of variable scope, with no consensus reached on whether new instances of functions are created or if existing instances are reused.

Contextual Notes

Participants note the importance of understanding closures and scope in JavaScript, as well as the potential impact on memory management when using anonymous functions extensively.

Michael27
Messages
24
Reaction score
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);
        }
    );
}
 
Technology news on Phys.org
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.
 
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.
 
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.
 
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.
JorisL said:
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   Reactions: Michael27
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!
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
Replies
2
Views
6K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K