Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's up with `return function()` in javascript anonymous functions nowadays? (BEST PRACTICES) [closed]

Tags:

javascript

NOTE: Updated and rewritten

This question has been redone and updated. Please pardon outdated references below. Thanks.

I've seen a lot of javascript code lately that looks wrong to me. What should I suggest as a better code pattern in this situation? I'll reproduce the code that I've seen and a short description for each one:

Code block #1

This code should never evaluate the inner function. Programmers will be confused because the code should run.

$(document).ready( function() { 
  return function() { 
    /* NOPs */
  }
});

Code block #2

The programmer likely intends to implement a self-invoking function. They didn't completely finish the implementation (they're missing a () at the end of the nested paren. Additionally, because they aren't doing anything in the outer function, the nested self-invoking function could be just inlined into the outer function definition.

Actually, I don't know that they intend a self invoking function, because the code is still wrong. But it appears they want a self invoking function.

$(document).ready( (function() { 
  return function() { 
    /* NOPs */
  }
}));

Code block #3

Again it appears the programmer is trying to use a self-invoking function. However, in this case it is overkill.

$(document).ready( function() { 
  (return function() { 
    /* NOPs */
  })()
}); 

Code block #4

an example code block

$('#mySelector').click( function(event) { 
  alert( $(this).attr('id') );

  return function() { 
    // before you run it, what's the value here?
    alert( $(this).attr('id') );
  }
});

Commentary:

I guess I'm just frustrated because it causes creep bugs that people don't understand, changes scoping that they're not grokking, and generally makes for really weird code. Is this all coming from some set of tutorials somewhere? If we're going to teach people how to write code, can we teach them the right way?

What would you suggest as an accurate tutorial to explain to them why the code they're using is incorrect? What pattern would you suggest they learn instead?


All the samples I've seen that have caused me to ask this question have been on SO as questions. Here's the latest particular snippet I've come across that exhibits this behavior. You'll notice that I'm not posting a link to the question, since the user appears to be quite the novice.

$(document).ready(function() {
 $('body').click((function(){
  return function()
  {
   if (counter == null) {
    var counter = 1;
   }
   if(counter == 3) {
     $(this).css("background-image","url(3.jpg)");
     $(this).css("background-position","10% 35%");
     var counter = null;
   }
   if(counter == 2) {
     $(this).css("background-image","url(2.jpg)");
     $(this).css("background-position","10% 35%");
     var counter = 3;
   }
   if(counter == 1) {
     $(this).css("background-image","url(1.jpg)");
     $(this).css("background-position","40% 35%");
     var counter = 2;
   }


  }
 })());
});

Here's how I proposed that they rewrite their code:

var counter = 1;
$(document).ready(function() {
    $('body').click(function() {
        if (counter == null) {
            counter = 1;
        }
        if (counter == 3) {
            $(this).css("background-image", "url(3.jpg)");
            $(this).css("background-position", "10% 35%");
            counter = 1;
        }
        if (counter == 2) {
            $(this).css("background-image", "url(2.jpg)");
            $(this).css("background-position", "10% 35%");
            counter = 3;
        }
        if (counter == 1) {
            $(this).css("background-image", "url(1.jpg)");
            $(this).css("background-position", "40% 35%");
            counter = 2;
        }
    });
});

Notice that I'm not actually saying my code is better in any way. I'm only removing the anonymous intermediary function. I actually know why this code doesn't originally do what they want, and I'm not in the business of rewriting everyone's code that comes along, but I did want the chap to at least have usable code.

I thought that a for real code sample would be appreciated. If you really want the link for this particular question, gmail me at this nick. He got several really good answers, of which mine was at best mid-grade.

like image 677
jcolebrand Avatar asked Oct 15 '10 19:10

jcolebrand


2 Answers

Your first example is strange. I'm not even sure if that would work the way the author likely intended it. The second simply wraps the first in unnecessary parens. The third makes use of a self-invoking function, though since the anonymous function creates its own scope (and possibly a closure) anyways, I'm not sure what good it does (unless the author specified additional variables within the closure - read on).

A self-invoking function takes the pattern (function f () { /* do stuff */ }()) and is evaluated immediately, rather than when it is invoked. So something like this:

var checkReady = (function () {
    var ready = false;
    return {
        loaded: function () { ready = true; },
        test: function () { return ready; }
    };
}())
$(document).ready(checkReady.loaded);

creates a closure binding the object returned as checkready to the variable ready (which is hidden from everything outside the closure). This would then allow you to check whether the document has loaded (according to jQuery) by calling checkReady.test(). This is a very powerful pattern and has a lot of legitimate uses (namespacing, memoization, metaprogramming), but isn't really necessary in your example.

EDIT: Argh, I misunderstood your question. Didn't realize you were calling out poor practices rather than asking for clarification on patterns. More to the point on the final form you asked about:

(function () { /* woohoo */ }())
(function () { /* woohoo */ })()
function () { /* woohoo */ }()

evaluate to roughly the same thing - but the first form is the least likely to have any unintended consequences.

like image 152
C-Mo Avatar answered Oct 21 '22 16:10

C-Mo


Anonymous functions are useful for:

  • Passing logic to another function
  • Declaring single use functions
  • Declaring a function without adding a variable to the scope
  • Providing scope for variables
  • Dynamic programming

You can read more on these topics at the following link: javascript anonymous functions

like image 32
Michael Goldshteyn Avatar answered Oct 21 '22 17:10

Michael Goldshteyn