Answer the question
In order to leave comments, you need to log in
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
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.
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); // <- в данном случае мы передали ссылку на функцию
An anonymous function is a function without a name.
function() { ... }
function funcWithName() { ... }
$( document ).ready(function() {
// Handler for .ready() called.
});
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; // тИ кто???
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question