A
A
Alexander2015-05-19 19:29:33
JavaScript
Alexander, 2015-05-19 19:29:33

What is an anonymous function and what is it eaten with?

Hello. Please tell us what an anonymous function is, what it is for, and how it is used in practice. And also, as far as I know, it is used in closures - I would like to know about this too.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Sergey, 2015-05-19
Protko @Fesor

An anonymous function (you can also come across such a name as lambdas) is a function without a name. It can be used at the time of declaration, it can be assigned to a variable, you can do all sorts of other things. If you want to know what else you can do with them, welcome to the wonderful world of Lambda calculus and functional programming.

D
Denis Ineshin, 2015-05-19
@IonDen

Anonymous functions are very often used to execute some code in callbacks, where in general there is no need to create a separate named function for this action. For example:

button.addEventListener('click', function (event) {
    // эта анонимная функция будет вызвана при клике
}, false);

// или можно так, посложнее, но обычно это лишнее
function btnClick (event) {
    // это уже функция с именем
}
button.addEventListener('click', btnClick, false); // <-  в данном случае мы передали ссылку на функцию

Closures are such a technique for storing hidden data, and here, of course, you can also use anonymous functions, but that's not the point.

A
Alexander Tartmin, 2015-05-19
@baskerville42

An anonymous function is a function without a name.

function() { ... }
function funcWithName() { ... }

Here is the best use case
$( document ).ready(function() {
  // Handler for .ready() called.
});

I have never heard of closures using an anonymous function...

Y
Ytsu Ytsuevich, 2015-05-19
@kofon

You can also break your head with this:

function getFunction(name){
  if (!name) return function(){ return "Who are you?" }
  else       return function(){ return "Hello " + name; }
}

// Вызов
var petya   = getFunction("Петя");
var unknown = getFunction();

petya();  // петя
unknown;  // тИ кто???

Need an explanation? If so, I'll explain!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question