简体   繁体   English

Jquery ready()vs之前的简单函数调用</body>

[英]Jquery ready() vs simple function call before </body>

If I'm calling my JS scripts just before the closing body tag, is there a difference between using jQuery ready function like $(myfunc()); 如果我在关闭body标记之前调用我的JS脚本,那么使用jQuery ready函数(如$(myfunc()); vs just using simply myfunc(); vs只使用简单的myfunc(); ?

Only one difference would exist: 只存在一个差异:

When you use $(function(){...}) (short for $(document).ready(function(){...}) , you're automatically wrapping the code in an anonymous function, thus creating a private scope. Variables defined using var inside this scope aren't leaked to the global scope. 当你使用$(function(){...})$(document).ready(function(){...})缩写$(document).ready(function(){...}) ,你会自动将代码包装在匿名函数中,从而创建一个私有函数范围。使用此范围内的var定义的变量不会泄露到全局范围。

<script>
$(function(){ //<-- Anonymous function wrapper
   var test = 1; //"Private" variable
   alert(test); //Alert: 1
});
alert(window.test); //Nothing
</script>
<body>

Versus

<script>
var test = 1;
alert(test); //Alert: 1
alert(window.test); //Alert: 1
</script>
</body>


When you don't wrap the function call in a wrapper, both approaches have a similar result: 如果不将函数调用包装在包装器中,则两种方法都会产生类似的结果:

 <script> $(myfunc); </script></body> </bodY><script> myfunc(); </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM