Home  >  Q&A  >  body text

Why do I sometimes use function(){} and sometimes not?

Why function(){} is sometimes used. ($(".banner .num li").hover(function(){var index=$(this).index();//Get the index value of the current elementi=index;$(".banner .img").stop().animate({left:index*1600},500)$(this) .addClass("onn").siblings().removeClass("onn"), sometimes not necessary ($(".banner .img").append(zqh);)


})


谭生谭生2610 days ago1299

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-26 17:47:25

    (function(){
    })();//立即执行

    Self-executing anonymous function:

    Common format: (function() { /* code */ })();

    Explanation: The first pair of brackets surrounding the function (function(){}) returns unnamed to the script function, followed by a pair of empty brackets to immediately execute the returned unnamed function, with the parameters of the anonymous function inside the brackets.

    Function: You can use it to create a namespace. As long as you write all your code in this special function package, it will not be accessible from the outside unless you allow it (add window before the variable, so that the function or variable becomes global). The code of each JavaScript library is basically organized in this form.

    To summarize, the execution function is mainly used for anonymous and automatic execution. The code is already running when it is interpreted.

    Other ways to write

    (function () { /* code */ } ()); 
    !function () { /* code */ } ();
    ~function () { /* code */ } ();
    -function () { /* code */ } ();
    +function () { /* code */ } ();
    $(function(){
    });//文档加载完后执行


    reply
    2
  • Cancelreply