[英]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>
<script> $(myfunc); </script></body> </bodY><script> myfunc(); </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.