Ok I figured it out after doing some research but I will leave the answer in for others.
Basically it's to avoid conflicts with other javascript libraries which also use the dollarsign.
So Jquery advices to use jQuery or window.jQuery instead of the dollar sign. It's usually used in combination with jQuery.noConflict() to make jQuery give up on the $ sign used in other javascript libraries when you mix libraries.
This is actually a way of running a self-executing function that passes in the window.jQuery object and passes it on to the $ sign. This way you can keep using the dollar sign in your code without having to worry about other javascript libraries that could cause a conflict with your code.
Wrapping it up in this function saves yourself from using window.jQuery everywhere to replace the $ sign.
If you execute function () {}() like this it results in a syntax error as it's just a function declaration. The ! turns it into an expression which can be executed.
So basically you can use both for the same purpose.
!function($){}()
(function($){})()
Feel free to modify or complement.
-----------------------------------------------------------------------------------------------
翻译:好吧,我在做了一些研究之后发现了这个问题,但我会把答案留给别人。
基本上,它是为了避免与其他使用美元符号的javascript库发生冲突。
因此,Jquery建议使用Jquery或window。用jQuery代替美元符号。它通常与jQuery. noconflict()一起使用,以使jQuery放弃在混合库时在其他javascript库中使用的$符号。
这实际上是一种运行自执行函数的方式,该函数将传入窗口。jQuery对象并将其传递到$符号。这样,您就可以继续在代码中使用美元符号,而不必担心会导致与代码冲突的其他javascript库。
在这个函数中包装它可以避免使用窗口。到处都有jQuery来替换$符号。
如果像这样执行函数(){}(),就会导致语法错误,因为它只是一个函数声明。!将其转换为可执行的表达式。
所以基本上你可以同时使用它们。
!function($){ }()
(function($){ })()
请随意修改或补充
浙公网安备 33010602011771号