Java Javascript: Assigning anonymous functions to attributes

AI Thread Summary
The discussion centers on the behavior of anonymous functions in JavaScript, particularly regarding their instantiation and scope when assigned as event handlers. Each time the `createElemA` function is called, a new instance of the anonymous function is created, allowing it to maintain its own context and access variables like `myid` if uncommented. The concept of closures is highlighted, explaining that the function retains access to its scope even after the outer function has executed. The conversation also touches on performance concerns, noting that excessive use of anonymous functions can lead to increased memory usage and potential garbage collection issues. Overall, understanding closures and function scope is crucial for effective JavaScript programming.
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 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!
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Replies
4
Views
1K
Replies
3
Views
2K
Replies
9
Views
2K
Replies
3
Views
2K
Replies
6
Views
3K
Replies
2
Views
1K
Replies
10
Views
3K
Back
Top