Why do you need to invoke an anonymous function on the same line?

前端 未结 19 1493
走了就别回头了
走了就别回头了 2020-11-22 00:17

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...:

//          


        
19条回答
  •  -上瘾入骨i
    2020-11-22 01:07

    This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

    alert(
        {foo: "I am foo", bar: "I am bar"}.foo
    ); // alerts "I am foo"
    

    Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

    Function.prototype.foo = function () {
        return function () {
            alert("foo");
        };
    };
    
    var bar = (function () {}).foo();
    
    bar(); // alerts foo
    

    And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

    var x = function () {} (); // this function is executed but does nothing
    
    function () {} (); // syntax error
    

    One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

    var obj = new function () {
        this.foo = "bar";
    };
    
    var obj = {
        foo : "bar"
    };
    

提交回复
热议问题