Javascript: Assigning anonymous functions to attributes

In summary: No, no objects are being kept alive. It's just that the function will be executed again when you click the element.The keyword is scope, it tells you which functions, variables and whatnot are available.A quick scan of Stack Overflow seems to answer some of the questions you have.Thank you Joris.
  • #1
Michael27
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);
        }
    );
}
 
Technology news on Phys.org
  • #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
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
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
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
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
  • #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!
 

Related to Javascript: Assigning anonymous functions to attributes

1. What are anonymous functions in Javascript?

Anonymous functions in Javascript are functions that do not have a name. They are often used as callbacks or assigned to attributes as event handlers.

2. How do you assign an anonymous function to an attribute in Javascript?

To assign an anonymous function to an attribute in Javascript, you can use the following syntax: element.attribute = function() { //code goes here }

3. What is the purpose of assigning anonymous functions to attributes in Javascript?

Assigning anonymous functions to attributes in Javascript allows you to define event handlers or callbacks directly in the HTML code without the need for a separate function. This can make your code more concise and easier to read.

4. Can anonymous functions be called by name in Javascript?

No, anonymous functions cannot be called by name in Javascript as they do not have a name. They can only be executed by calling the attribute to which they are assigned.

5. Are there any limitations to using anonymous functions in Javascript?

One limitation of using anonymous functions in Javascript is that they cannot be reused, as they do not have a name. Additionally, if an error occurs in an anonymous function, it can be difficult to debug as it does not have a name to identify it by.

Similar threads

  • Programming and Computer Science
Replies
9
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
5K
  • Programming and Computer Science
Replies
4
Views
1K
  • Computing and Technology
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
10
Views
3K
  • Programming and Computer Science
Replies
5
Views
3K
  • Programming and Computer Science
Replies
2
Views
13K
Back
Top