JavaScript 中自我声明匿名函数之前的美元符号?
这两者有什么区别:
$(function () {
// do stuff
});
AND
(function () {
// do stuff
})();
What is the difference between these two:
$(function () {
// do stuff
});
AND
(function () {
// do stuff
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
第一个使用 jQuery 将函数绑定到
document.ready
事件。第二个声明并立即执行一个函数。The first uses jQuery to bind a function to the
document.ready
event. The second declares and immediately executes a function.$(function() {});
是 jQuery 的快捷方式,而
(function() {})();
是立即调用的函数表达式,即 IIFE。这意味着它是一个表达式(而不是语句),并且在创建后立即被调用。$(function() {});
is a jQuery shortcut forWhile
(function() {})();
is a instantly invoked function expression, or IIFE. This means that its an expression (not a statement) and it is invoked instantly after it is created.它们都是匿名函数,但是
(function(){})()
会立即调用,而$(function(){})
在文档准备好时调用。jQuery 的工作原理是这样的。
因此,您只需调用 jQuery 函数并传入一个函数,该函数将在文档准备就绪时调用。
‘自执行匿名函数’与这样做是一样的。
唯一的区别是您没有污染全局名称空间。
They are both anonymous functions, but
(function(){})()
is called immediately, and$(function(){})
is called when the document is ready.jQuery works something like this.
So you're just calling the jQuery function and passing in a function, which will be called on document ready.
The 'Self-executing anonymous function' is the same as doing this.
The only difference is that you are not polluting the global namespace.
一个是 jquery
$(document).ready
函数,另一个只是一个调用自身的匿名函数。one is a jquery
$(document).ready
function and the other is just an anonymous function that calls itself.一旦文档准备好,这个函数就会执行,这意味着整个 HTML 应该在执行之前加载,但在第二种情况下,该函数在创建后立即调用。
This function execution once documents get ready mean, the whole HTML should get loaded before its execution but in the second case, the function invoked instantly after it is created.