不是自我调用匿名函数 [英] Not self invoking anonymous functions

查看:76
本文介绍了不是自我调用匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bootstrap css使用以下内容:

Bootstrap css uses the following:

!function( $ ) {
}( window.jQuery )

这与我最初学习的自调用匿名函数调用不同:

That's different than the self-invoking anonymous function call that I originally learned:

(function($) {
})(jQuery);

问:您认为这只是偏好吗?我的意思是not符号而不是括号括起来。

Q: Is that just preference you think? I mean the not symbol instead of enclosing it in parenthesis.

推荐答案


问:这只是你认为的偏好吗?

是的,但是使用一元运算符,当您在​​IIFE之前忘记分号时可以避免一些错误,这可能导致()被解释为函数调用。 / p>

Yes, but using a unary ! operator, you can avoid a few bugs when you forget a semicolon before the IIFE, which can cause the () to be interpreted as a function call.

alert('foo')  // alerts 'foo'

(function() {  // TypeError: undefined is not a function
    alert('bar');
})()

这里外部()被解释为函数调用。它试图调用从 alert()函数返回的任何内容,当然返回 undefined ,这不是一个函数。

Here the outer () is interpreted as a function call. It's trying to call whatever was returned from the alert() function, which of course returns undefined, which isn't a function.

alert('foo')  // alerts 'foo'

!function() {
    alert('bar');  // alerts 'bar'
}()

这个没有麻烦,因为是一个一元运算符,只计算右边的操作数。

No troubles with this one, since the ! is a unary operator that only evaluates the operand to its right.

这篇关于不是自我调用匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆