Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to refer to an anonymous function within the function itself?

if arguments.callee is not allowed in "use strict", and we can't do

var f = function g() {
    //g
}

because in IE that wouldn't work (or that would work "weirdly") http://kangax.github.com/nfe/#jscript-bugs, then what other options do we have to refer to the anonymous function within the function itself?

like image 819
Pacerier Avatar asked Apr 22 '11 16:04

Pacerier


People also ask

Can we assign anonymous function in JavaScript?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.

How do you call an anonymous function?

In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambdas or lambda abstractions.

Can you transfer an anonymous function to another function as an argument?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.


2 Answers

That's precisely what the Y combinator is for.

Here's an article by James Coglan about deriving the Y combinator in JavaScript.

like image 126
Jörg W Mittag Avatar answered Oct 06 '22 20:10

Jörg W Mittag


Don't use a named function expression. Just declare and initialize it the normal way.

function f() {
    f();
}

The only viable alternative with ES5 strict is to use the code in your question, and deal with IE's crappy NFE implementation. But: do you really expect a browser that gets NFEs so horribly wrong (ahem, IE) to implement "use strict" anytime soon?

like image 34
Matt Ball Avatar answered Oct 06 '22 21:10

Matt Ball