When to use anonymous JavaScript features?

I am trying to figure out when to use anonymous JavaScript functions.

State differences between functions? Explain when you will use each.

var test1 = function(){
    $("<div />").html("test1").appendTo(body)
};

function test2() {
    $("<div />").html("test2").appendTo(body)
}

I think the answer is that one uses an anonymous function and the other does not replace an empty div element. Is it correct?

+3
source share
3 answers

In your example, this really doesn't really matter much. The only difference is that functions declared with help function foo() { }are available anywhere in the same space at any time, and functions declared with help var foo = function () { }are available only after the code executing the task has been run.

foo(); // ok
function foo() { ... };

bar(); // error, bar is not a function
var bar = function () { ... };
bar(); // ok

, :

arr.sort(function (a, b) { return a - b; });  // anonymous callback function

function MyObject() {
    this.foo = function () { ... }  // object constructor
}
+6

, , ( ):

(function() {
    var pollution = 'blablabla';

    function stinky() {
        // Some code
    }
})();
+1

You can check out John Resig JavaScript Library Secrets , especially for feature 47 for JavaScript. Pretty much, but you'll learn more about JavaScript

+1
source

All Articles