Questions tagged [anonymous-function]
Anonymous functions use a block of code as a value, defining it as an inline function without a name.
2,133
questions
404
votes
10
answers
82k
views
Explain the encapsulated anonymous function syntax
Summary
Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but this doesn't: function(){}();?
What I know
In ...
391
votes
19
answers
302k
views
Why do you need to invoke an anonymous function on the same line?
I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as ...
342
votes
5
answers
592k
views
How to sort with lambda in Python
I am trying to sort some values by attribute, like so:
a = sorted(a, lambda x: x.modified, reverse=True)
I get this error message:
<lambda>() takes exactly 1 argument (2 given)
Why? How do I ...
245
votes
6
answers
45k
views
Anonymous recursive PHP functions
Is it possible to have a PHP function that is both recursive and anonymous? This is my attempt to get it to work, but it doesn't pass in the function name.
$factorial = function( $n ) use ( $...
156
votes
18
answers
175k
views
removeEventListener on anonymous functions in JavaScript
I have an object that has methods in it. These methods are put into the object inside an anonymous function. It looks like this:
var t = {};
window.document.addEventListener("keydown", function(e) {
...
141
votes
21
answers
87k
views
javascript: recursive anonymous function?
Let's say I have a basic recursive function:
function recur(data) {
data = data+1;
var nothing = function() {
recur(data);
}
nothing();
}
How could I do this if I have an ...
126
votes
1
answer
46k
views
Why do arrow functions not have the arguments array? [duplicate]
function foo(x) {
console.log(arguments)
} //foo(1) prints [1]
but
var bar = x => console.log(arguments)
gives the following error when invoked in the same way:
Uncaught ReferenceError: ...
113
votes
4
answers
16k
views
Location of parenthesis for auto-executing anonymous JavaScript functions?
I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self executed.
The code used to ...
105
votes
6
answers
158k
views
PHP 7.2 Function create_function() is deprecated
I have used create_function() in my application below.
$callbacks[$delimiter] = create_function(
'$matches',
"return '$delimiter' . strtolower(\$matches[1]);"
);
But for PHP 7.2.0, ...
103
votes
11
answers
118k
views
Is it valid to define functions in JSON results?
Part of a website's JSON response had this (... added for context):
{..., now:function(){return(new Date).getTime()}, ...}
Is adding anonymous functions to JSON valid? I would expect each time you ...
103
votes
5
answers
34k
views
Why use named function expressions?
We have two different way for doing function expression in JavaScript:
Named function expression (NFE):
var boo = function boo () {
alert(1);
};
Anonymous function expression:
var boo = ...
102
votes
4
answers
49k
views
Lambda in a loop [duplicate]
Considering the following code snippet:
# directorys == {'login': <object at ...>, 'home': <object at ...>}
for d in directorys:
self.command["cd " + d] = (lambda : self.root....
99
votes
4
answers
42k
views
Why is "this" in an anonymous function undefined when using strict?
Why is this in an anonymous function undefined when using javascript in strict mode? I understand why this could make sense, but I couldn't find any concrete answer.
Example:
(function () {
"use ...
98
votes
5
answers
51k
views
php is_function() to determine if a variable is a function
I was pretty excited to read about anonymous functions in php, which let you declare a variable that is function easier than you could do with create_function. Now I am wondering if I have a function ...
98
votes
6
answers
160k
views
How can I write an anonymous function in Java?
Is it even possible?
97
votes
2
answers
34k
views
How to call a closure that is a class variable?
class MyClass {
var $lambda;
function __construct() {
$this->lambda = function() {echo 'hello world';};
// no errors here, so I assume that this is legal
}
}
$myInstance = new ...
95
votes
2
answers
122k
views
How can I pass a reference to a function, with parameters? [duplicate]
Possible Duplicate:
How can I pre-set arguments in JavaScript function call? (Partial Function Application)
I need to able to pass a reference to a function with a given set of parameters.
Here ...
93
votes
6
answers
100k
views
How to removeEventListener that is addEventListener with anonymous function?
function doSomethingWith(param)
{
document.body.addEventListener(
'scroll',
function()
{
document.write(param);
},
false
); // An event that ...
91
votes
5
answers
59k
views
Using `$this` in an anonymous function in PHP pre 5.4.0
The PHP manual states
It is not possible to use $this from anonymous function before PHP
5.4.0
on the anonymous functions page. But I have found I can make it work by assigning $this to a ...
86
votes
4
answers
30k
views
Anonymous function shorthand
There's something I don't understand about anonymous functions using the short notation #(..)
The following works:
REPL> ((fn [s] s) "Eh")
"Eh"
But this doesn't:
REPL> (#(%) "Eh")
This ...
83
votes
3
answers
56k
views
Use keyword in functions - PHP [duplicate]
Possible Duplicate:
In Php 5.3.0 what is the Function “Use” Identifier ? Should a sane programmer use it?
I've been examining the Closures in PHP and this is what took my attention:
...
82
votes
6
answers
55k
views
What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?
I'm new-ish to JavaScript. I understand many of the concepts of the language, I've been reading up on the prototype inheritance model, and I'm whetting my whistle with more and more interactive front-...
79
votes
1
answer
30k
views
Closure vs Anonymous function (difference?) [duplicate]
Possible Duplicates:
What is Closures/Lambda in PHP or Javascript in layman terms?
What is the difference between a 'closure' and a 'lambda'?
Hi,
I have been unable to find a ...
73
votes
2
answers
42k
views
Callback function using variables calculated outside of it
Basically I'd like to do something like this:
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$avg = array_sum($arr) / count($arr);
$callback = function($val){ return $val < $avg };
return array_filter($...
73
votes
4
answers
72k
views
Javascript anonymous function call [duplicate]
I was reading JS sources from Twitter — on my way to improve my JS knowledge base, when I came across the strange way of calling anonymous function:
!function( $ ) {
...
}( window.jQuery );
...
65
votes
5
answers
36k
views
Javascript 'colon' for labeling anonymous functions?
What does this code refer too?
queryString: function() {
//some code
}
I tested it in the WebConsole (Firefox) but it wouldn't execute, so I'm thinking that it isn't equivalent to function ...
65
votes
1
answer
16k
views
Is it possible to set a breakpoint in anonymous functions?
I quickly want to determine whether/when a set of events are triggered. Therefore I quickly assigned empty lambda's to them.
_session.TopologyStarted += () => { };
When tracing through the code ...
64
votes
4
answers
29k
views
JavaScript anonymous function immediate invocation/execution (expression vs. declaration) [duplicate]
Possible Duplicates:
What is the difference between a function expression vs declaration in JavaScript?
Explain JavaScript's encapsulated anonymous function syntax
Why this:
(function () {
...
62
votes
3
answers
6k
views
(...()) vs. (...)() in javascript closures [duplicate]
I know this is silly, but there's any difference between this:
(function() {
var foo = 'bar';
})();
and this?
(function() {
var foo = 'bar';
}());
JSLint tells us to Move the ...
60
votes
4
answers
31k
views
Anonymous functions using GCC statement expressions
This question isn't terribly specific; it's really for my own C enrichment and I hope others can find it useful as well.
Disclaimer: I know many will have the impulse to respond with "if you're ...
56
votes
4
answers
25k
views
Python: pass statement in lambda form
A Python newbie question, why is this syntax invalid: lambda: pass, while this: def f(): pass is correct?
Thanks for your insight.
55
votes
14
answers
41k
views
Choose Python function to call based on a regex
Is it possible to put a function in a data structure, without first giving it a name with def?
# This is the behaviour I want. Prints "hi".
def myprint(msg):
print msg
f_list = [ myprint ]
f_list[...
55
votes
4
answers
18k
views
How to pass two anonymous functions as arguments in CoffeScript?
I want to pass two anonymous functions as arguments for jQuery's hover, like so:
$('element').hover(
function() {
// do stuff on mouseover
},
function() {
// do stuff on mouseout
}
);
...
47
votes
9
answers
21k
views
Why use anonymous function? [duplicate]
Possible Duplicate:
How do you use anonymous functions in PHP?
Why should i use an anonymous function? I mean, what's the real deal using it?
I just don't really get this. I mean, you use ...
46
votes
6
answers
48k
views
Why and how do you use anonymous functions in PHP?
Anonymous functions are available from PHP 5.3.
Should I use them or avoid them? If so, how?
Edited: just found some nice trick with PHP anonymous functions:
$container = new ...
46
votes
7
answers
8k
views
Anonymous recursive function in Scala
Is there a way to write an anonymous function that is recursive in Scala? I'm thinking of something like this:
((t: Tree) => {
print(t.value);
for (c <- t.children)
thisMethod(c)...
44
votes
5
answers
22k
views
How to execute multiple statements in a MATLAB anonymous function?
I'd like to do something like this:
>> foo = @() functionCall1() functionCall2()
So that when I said:
>> foo()
It would execute functionCall1() and then execute functionCall2(). (I ...
43
votes
3
answers
28k
views
How can I access local variables from inside a C++11 anonymous function?
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):
float tot = std::...
42
votes
2
answers
38k
views
Difference between function with a name and function without name in Javascript
1.
function abc(){
alert("named function");
}
v/s
2.
function(){
alert("Un-Named function");
}
Kindly explain from beginners point.
41
votes
5
answers
10k
views
Dollar sign before self declaring anonymous function in JavaScript?
What is the difference between these two:
$(function () {
// do stuff
});
AND
(function () {
// do stuff
})();
40
votes
4
answers
17k
views
Can you name the parameters in a Func<T> type?
I have a "dispatch map" defined as such:
private Dictionary<string, Func<DynamicEntity, DynamicEntity, IEnumerable<DynamicEntity>, string>> _messageProcessing;
This allows me to ...
40
votes
4
answers
16k
views
Anonymous functions in WordPress hooks
WordPress hooks can be used in two ways:
using callback function name and appropriate function
add_action( 'action_name', 'callback_function_name' );
function callback_function_name() {
// do ...
39
votes
5
answers
19k
views
What does this "(function(){});", a function inside brackets, mean in javascript? [duplicate]
Possible Duplicates:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
What do parentheses surrounding a JavaScript object/function/class declaration mean?
Hi All
I don't ...
38
votes
5
answers
8k
views
Recursion and anonymous functions in elixir
I'm trying to define an anonymous function to do a dot product, I can code this as a private function without any problem but I am struggling with the anonymous function syntax.
I know I could ...
38
votes
4
answers
33k
views
this value in JavaScript anonymous function
Can anybody explain to me why A is true and B is false? I would have expected B to be true as well.
function MyObject() {
};
MyObject.prototype.test = function () {
console.log("A", this ...
36
votes
4
answers
97k
views
Best way to run a simple function on a new Thread?
I have two functions that I want to run on different threads (because they're database stuff, and they're not needed immediately).
The functions are:
getTenantReciept_UnitTableAdapter1....
36
votes
4
answers
14k
views
Difference between expression lambda and statement lambda
Is there a difference between expression lambda and statement lambda?
If so, what is the difference?
Found this question in the below link but could not understand the answer
What is Expression ...
36
votes
2
answers
30k
views
Return value from anonymous function postgresql
How to?
For easy example. I have a simple function:
DO LANGUAGE plpgsql $$ DECLARE
BEGIN
EXECUTE 'SELECT NOW()';
END $$;
How I can return value of "NOW()" or other values from also anonymous ...
35
votes
9
answers
52k
views
Can I store RegExp and Function in JSON?
Given a block like this:
var foo = {
"regexp": /^http:\/\//,
"fun": function() {},
}
What is a proper way to store it in JSON?
35
votes
2
answers
13k
views
How to document anonymous functions (closure) with jsdoc-toolkit
I am trying to document my code using JSDoc-toolkit. My code starts by being wrapped with a self-executing anonymous function. How in the world do I document this? I've spent nearly all day on this. ...