Roli Agrawal
Roli Agrawal

Reputation: 2466

difference between making callback function as anonymous and from name

I was watching one video on topic memory leak in JavaScript which says callback from named function are better than anonymous function in term of memory leak. so what the difference when i use callback as anonymous vs named.

$("#abc").click(function() {
    console.log("hello")
})

and

$("#abc").click(somethingclick);

function somethingclick() {
    console.log("hello")
};

Upvotes: 4

Views: 93

Answers (1)

t.niese
t.niese

Reputation: 40842

This isn't an answer but a longer comment.

The video is misleading at the place where the speaker says try to avoid anonymous functions for events.

There is no difference between:

$("#abc").click(function() {
   console.log("hello")
});

and

$("#abc").click(somethingclick);
// no other code in between here
function somethingclick() {
   console.log("hello")
};

Because both functions have the same scope and will as of that keep the same variables alive (In your example there isn't even any variable that is kept alive).

What the speaker wants to tell you is that you should avoid using scopes to keep variables available for the callback, because this increases the probability that you keep objects in memory that you don't want to keep alive.

Also other parts of the video/slides are misleading, because the speaker claims to use jQuery in the slides, but the syntax is clearly not valid.

Upvotes: 3

Related Questions