javascriptjqueryself-invoking-function

Self invoking function inside jQuery event is not working


Self invoking function defined inside jQuery event is not working, but why?

$('div').on('click', function(){
  $('div').text($('div').text() + 1)
  (function(){
    $('div').text($('div').text() + 0)
  })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>text</div>

Edit: Answers below are focused on this keyword so I've changed this parameter to 'div'. It still does not work.


Solution

  • Your problem is that you miss a ; at the end of $('div').text($('div').text() + 1)

    Without the ; it is the same as if you would write:

    $('div').text($('div').text() + 1)(function(){
       $('div').text($('div').text() + 0)
    })();
    

    But because text($('div').text() + 1) does not return a function, you will get this error.

    Uncaught TypeError: $(...).text(...) is not a function

    This is one situation where you have to use the ; to end your statement.

    ecma-262: 11.9.2 Examples of Automatic Semicolon Insertion

    The source

    a = b + c
    (d + e).print()
    

    is not transformed by automatic semicolon insertion, because the parenthesised expression that begins the second line can be interpreted as an argument list for a function call:

    a = b + c(d + e).print()
    

    So you have to write:

    $('div').text($('div').text() + 1);
    (function(){
       $('div').text($('div').text() + 0)
    })();